猫鼬子文档查询仅返回ID?

时间:2019-09-19 06:42:45

标签: mongoose mongoose-schema

由于某种原因,当我创建一个子文档并尝试将其作为子文档推送到父文档时,它仅保存模式ID。此外,当我尝试使用_id作为查询子文档时,它返回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)
            } )
        } )           
    })

是因为注册新用户时,初始化子文档字段entries错了吗?

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

1 个答案:

答案 0 :(得分:0)

您正在传递数组以查找一种方法,而应该在数组之前使用$ in。

像这样改变。

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