【问题标题】:populate fields of nested object in mongoose schema在猫鼬模式中填充嵌套对象的字段
【发布时间】:2018-10-15 21:21:02
【问题描述】:

我有这两个模型

var postSchema = new Schema({
  content : String,
  author : [{
    user : {
    type: Schema.ObjectId,
    ref: 'user'
    },
    bool: Boolean
  }]
});


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

我正在尝试使用用户名填充 Post,而不是仅显示 [Object] 或 id 如果 i .toString it

我现在得到了什么:

{ author: [ [Object], [Object], [Object] ],
    _id: 5aedc4d3c534213279faec79,
    content: 'hello',
    __v: 0 } ]

用 .toString() 我得到

{ author: 
   [ { _id: 5aedc364ce3b022d4ff74922,
       user: 5aedb9e47e055d1ac26aa572,
       bool: true } ]

我想要什么:

{ author: 
   [ { _id: 5aedc4d3c534213279faec7c,
       user: "Some name here", //( name instead of user _id )
       bool: true },
     { _id: 5aedc4d3c534213279faec7b,
       user: "Some name here",
       bool: false },
     { _id: 5aedc4d3c534213279faec7a,
       user: "Some name here",
       bool: true } ],
  _id: 5aedc4d3c534213279faec79,
  content: 'hello',
  __v: 0 }

这可能吗?

【问题讨论】:

  • 查询码是多少?

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

您可以使用带有嵌套语法的填充方法

const Post = mongoose.model('Post', postSchema);
const User = mongoose.model('User', userSchema);

Post
    .find({})
    .populate({path:'author.user', 'model':'User'})
    .exec((err, posts) => {
        if (err) return next(err);
        posts.forEach(post => {
          console.log(JSON.stringify( post, null, 2) ); // spacing level = 2
        }
    });

将为每个帖子输出(这并不完全符合您的要求,但希望您可以灵活地使用User 格式

{ 
  _id: 5aedc4d3c534213279faec79,
  content: 'some content',
  author: [ 
    {
    user: {_id: 5aedc4d3c534213279faec7c, "user name here"}
    bool: true 
    },
    {
    user: {_id: 5aedc4d3c534213279faec7b, "user name 2 here"}
    bool: true 
    }
__v: 0 
}

参考 mongoose.populate http://mongoosejs.com/docs/populate.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-28
    • 2021-12-25
    • 2015-06-04
    • 2019-12-27
    • 2017-01-28
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多