【问题标题】:Mongoose subdocument query only returning ids?Mongoose 子文档查询仅返回 id?
【发布时间】:2020-01-20 03:22:10
【问题描述】:

由于某种原因,当我创建子文档并尝试将其作为子文档推送到父文档时,它只是保存了架构 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: []
    }
)

【问题讨论】:

  • 您检查了数据库是否正确插入数据库?
  • 您也需要显示您的架构。看起来你指定 entries 字段是你架构中的一个 id 数组。

标签: mongoose mongoose-schema


【解决方案1】:

您正在传递数组来查找一种方法,而不是在数组之前使用 $in。

这样改。

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

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 2023-04-09
    • 2015-04-27
    • 2021-12-26
    • 2016-01-09
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多