猫鼬中document.save()之后的错误人口

问题描述 投票:1回答:1

我正在尝试创建博客并以以下模式返回填充的博客:

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 
    }

但是作者填写错误。没有username,并且id是一个数组!

我在哪里出错了,以及如何解决?

node.js mongodb mongoose mongoose-populate
1个回答
0
投票

您可以在下面的代码行中添加以查看代码中发生的事情:

mongoose.set('debug', true);

[第一句:await newBlog.save();触发设置了insertOne的文档的author操作:author: ObjectId("...")

然后您运行await foundUser.save();,该操作显式设置了一系列博客文章:

{ '$set': { blogPosts: [ ObjectId(...), ObjectId(...) ] }

这很有意义,因为您在JS代码中使用了concat。事实是,没有其他第三条查询,因为您要在无法使用的现有内存中对象上运行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: {} })
© www.soinside.com 2019 - 2024. All rights reserved.