我正在尝试创建一个博客并返回以下模式中填充的博客:
const blogSchema = new mongoose.Schema({
title: {
type:String
},
author: {
type: mongoose.Schema.Types.ObjectID,
ref: 'UserTable',
required: true
}
});
module.exports = mongoose.model('BlogPostTable', blogSchema);
和
const userSchema = new mongoose.Schema({
username:{
type:String,
},
blogPosts: [
{
type: mongoose.Schema.Types.ObjectID,
ref: 'BlogPostTable'
}
]
});
module.exports = mongoose.model('UserTable', userSchema);
我正在保存这样的博客:
blogRouter.post('/', async (request, response, next) => {
const token = request.token;
try {
const foundUser = await userTable.findById(decodedToken.id); // Find User
const newBlog = new blogTable({ // Create document
title: request.body.title,
text: request.body.text,
likes: 0,
author: foundUser._id
});
await newBlog.save(); // Save Blog
foundUser.blogPosts = foundUser.blogPosts.concat(newBlog); // update Users blogs
await foundUser.save();
response.status(200).json(newBlog.populate('author').toJSON()); // WRONG OUTPUT
}
但是,
作者填写错误。没有用户名
,id
是一个数组!
我哪里出了问题以及如何解决?
最佳答案
您可以添加以下代码行来查看代码中发生的情况:
mongoose.set('调试', true);
第一条语句:await newBlog.save();
触发 insertOne
操作,文档的 author
设置为: author: ObjectId("...")
然后运行 awaitfoundUser.save();
显式设置博客文章数组:
{ '$set': { blogPosts: [ ObjectId(...), ObjectId(...) ] }
这是有道理的,因为您在 JS 代码中使用了 concat
。问题是,没有其他第三个查询,因为您尝试在现有内存对象上运行 populate
,但这是行不通的 - populate 需要查询而不是内存对象。
因此,您必须再次查询数据库才能填充author
:
let userPosts = await blogTable
.find({ author: foundUser._id })
.populate('author');
console.log(userPosts);
触发两个查询:
Mongoose: blogposttables.find({ author: ObjectId("...") }, { projection: {} })
Mongoose: usertables.find({ _id: { '$in': [ ObjectId("...") ] } }, { projection: {} })
关于node.js - Mongoose 中 document.save() 后的人口数量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60461320/