当前位置: 首页 > 面试题库 >

创建后如何在猫鼬中填充子文档?

黄德明
2023-03-14
问题内容

我要在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是我的猫鼬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)
        });
    });
});


 类似资料:
  • 问题内容: 一般而言,我对Mongoose和MongoDB还是很陌生,所以我很难确定是否可以进行以下操作: 有更好的方法吗? 编辑 如有任何混淆,我们深表歉意。我想做的是获取所有包含有趣标签或政治标签的商品。 编辑 没有where子句的文档: 使用where子句,我得到一个空数组。 问题答案: 对于大于3.2的现代MongoDB,您可以在大多数情况下用作替代。这也有实际上做加盟,而不是什么“在服务

  • 问题内容: 我在用猫鼬填充后无法通过在文档内部匹配的值来查询文档。 我的架构是这样的: 我想让所有用户拥有例如类型为“ Gmail”的电子邮件。 以下查询返回空结果: 我不得不像这样过滤JS中的结果: 有没有办法从猫鼬直接查询类似的东西? 问题答案: @Jason Cust 已经很好地解释了它- 在这种情况下,通常最好的解决方案是更改架构,以防止通过存储在单独集合中的文档的属性进行查询。 不过,这

  • 问题内容: 我无法手动或自动在新保存的对象上填充创建者字段……我能找到的唯一方法是重新查询我已经想要做的对象。 这是设置: 这是我拉头发的地方 编辑:最新的猫鼬解决了此问题并添加了填充功能,请参见新的接受的答案。 问题答案: 您应该能够使用模型的填充函数来执行此操作:http : //mongoosejs.com/docs/api.html#model_Model.populate 在书籍的保存处

  • 问题内容: 我将MongoDB和Mongoose用作我的ODM,并且试图在同一条语句中使用和进行查询。 这是我的简单文档模型: 我只是想获取一个用户的每条消息,并按与他交谈的每个用户分组。我这样尝试过: 但是,不幸的是,我的模型没有方法。您有什么解决方案可以使它正常工作吗? 谢谢。 问题答案: 使用$ lookup的示例填充,lookup填充为数组,因此$ unwind。

  • 问题内容: 如何在示例文档中填充“组件”: 这是我的JS,可从Mongoose获取文档: 问题答案: 猫鼬4.5支持此 您可以加入不止一个深层次

  • 如何在示例文档中填充“组件”: 这是我的JS,我在这里通过Mongoose获取文档: