【问题标题】:Wrong population after document.save() in mongoosemongoose 中 document.save() 后的错误人口
【发布时间】:2020-06-13 02:59:00
【问题描述】:

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

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 
    }

但是作者填写错误。没有usernameid 是一个数组!

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

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

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

    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: {} })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-22
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 2016-04-08
      • 2017-12-30
      相关资源
      最近更新 更多