Node.js mongoose中document.save()后填充错误
我正在尝试创建一个博客,并按以下模式返回填充的博客:Node.js mongoose中document.save()后填充错误,node.js,mongodb,mongoose,mongoose-populate,Node.js,Mongodb,Mongoose,Mongoose Populate,我正在尝试创建一个博客,并按以下模式返回填充的博客: const blogSchema = new mongoose.Schema({ title: { type:String }, author: { type: mongoose.Schema.Types.ObjectID, ref: 'UserTable', required: true } }); module.exports = mongoo
const blogSchema = new mongoose.Schema({
title: {
type:String
},
author: {
type: mongoose.Schema.Types.ObjectID,
ref: 'UserTable',
required: true
}
});
module.exports = mongoose.model('BlogPostTable', blogSchema);
及
我正在保存这样一个博客:
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('debug',true)代码>
第一条语句:等待newBlog.save()代码>对设置了作者
的文档触发insertOne
操作:作者:ObjectId(“…”
然后运行wait foundUser.save()代码>,它显式地设置blogpost数组:
{'$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: {} })
Mongoose: blogposttables.find({ author: ObjectId("...") }, { projection: {} })
Mongoose: usertables.find({ _id: { '$in': [ ObjectId("...") ] } }, { projection: {} })