Search code examples
mongoosemongoose-schema

Mongoose subdocument query only returning ids?


For some reason when I create a subdocument and try to push it onto a parent document as a child, it is only saving the schema ID. Furthermore when I try to query that subdocument, using _id as the query, it is returning null.

exports.entry_create = (req, res, next) => {

   let newEntry = new Entry
    (
        {
            title: req.body.title,
            tasks: [],
            minutesComplete: 0,
            hoursComplete: 0,
            pomodorosComplete: 0
        }
    )



    // { $push: { entries: newEntry } }
    const doc =  User.findOne({username: req.body.username}, (err, username) => {

        if (err){
            res.send(err)
        }

        username.entries.push(newEntry)

        var subdoc = username.entries[username.entries.length -1 ]

        console.log(subdoc) // ONLY RETURNS ID OF SUBDOC eg, "5d832104781697122217a1df"

        username.save( (err, prod) =>{
            console.log(prod.entries) // ["5d8320e20cce5311bca6cd1c" "5d832104781697122217a1df"]
            Entry.findOne({_id: prod.entries[ prod.entries.length - 1 ] } , (err, result) => { 

                console.log(result) // IS NULL

                res.send(result)
            } )
        } )           
    })

Is it because when I register a new user, I'm initializing the subdocument field entries wrong?

let user = new User(
    {
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        entries: []
    }
)

Solution

  • You are passing array to find one method instead you should user $in before the array.

    Change like this.

    Entry.findOne( { _id: { $in: prod.entries } } , (err, result) => { 
        console.log(result) // IS NULL
        res.send(result)
    })