node.js - 创建后如何在 mongoose 中填充子文档?

标签 node.js mongodb express mongoose

我正在向 item.comments 列表添加评论。在将其输出到响应中之前,我需要获取 comment.created_by 用户数据。我该怎么做?

    Item.findById(req.param('itemid'), function(err, item){
        var comment = item.comments.create({
            body: req.body.body
            , created_by: logged_in_user
        });

        item.comments.push(comment);

        item.save(function(err, item){
            res.json({
                status: 'success',
                message: "You have commented on this item",

//how do i populate comment.created_by here???

                comment: item.comments.id(comment._id)
            });
        }); //end item.save
    }); //end item.find

我需要在我的 res.json 输出中填充 comment.created_by 字段:

                comment: item.comments.id(comment._id)

comment.created_by 是我的 Mongoose CommentSchema 中的用户引用。它目前只给我一个用户 ID,我需要用所有用户数据填充它,除了密码和盐字段。

这是人们询问的架构:

var CommentSchema = new Schema({
    body          : { type: String, required: true }
  , created_by    : { type: Schema.ObjectId, ref: 'User', index: true }
  , created_at    : { type: Date }
  , updated_at    : { type: Date }
});

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , created_by  : { type: Schema.ObjectId, ref: 'User', index: true }
  , comments  : [CommentSchema]
});

最佳答案

为了填充引用的子文档,您需要显式定义 ID 引用的文档集合(如 created_by: { type: Schema.Types.ObjectId, ref: 'User' } )。

鉴于此引用已定义并且您的架构也已明确定义,您现在可以像往常一样调用 populate(例如 populate('comments.created_by') )

概念证明代码:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

最后请注意,populate 仅适用于查询,因此您需要先将项目传递到查询中,然后调用它:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

关于node.js - 创建后如何在 mongoose 中填充子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13026486/

相关文章:

angularjs - 无法 POST/api Node

javascript - Node.js 为 heroku 构建 json api

javascript - typescript 为 npm 包制作一个简单的 d.ts 文件

node.js - 为什么我的请求在循环时会被暂停?

node.js - NPM :Cannot find module 'bcrypt'

Javascript promise 不会通过 async/await 返回

元素数组中的数组上的 MongoDB 全文

node.js - Mongoose - 单例模型

node.js - 使用 MERN 堆栈和 socket.io 进行私有(private)聊天

javascript - 如何在 Node JS 中使用事件?