node.js - Mongoose 中 document.save() 后的人口数量错误

标签 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 = 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/

相关文章:

python - Django MongoDB 迁移警告

node.js - 在 MongooseJS 对象数组中查找特定属性

node.js - 使用 Sequelize 进行集成测试

java - Spring Boot数据,MongoDB不返回结果

javascript - 如何调试不会从 MongoDB 检索数据的 JavaScript?

java - 提高 MongoDB 查询性能

node.js - Mongoose 包含具有依赖关系的模型

javascript - 独特的验证在 Mongoose 中不起作用

javascript - typescript :按接口(interface)或类过滤对象

node.js - 在 WebStorm 和 SourceTree 中使用 NVM 时 Git Hooks 错误