【发布时间】: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 数组。