簡體   English   中英

在貓鼬模式中填充嵌套對象的字段

[英]populate fields of nested object in mongoose schema

我有這兩種模式

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


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

我正在嘗試使用用戶名填充Post,而不是僅顯示[Object]或ID(如果我使用.toString的話)

我現在得到的是:

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

這可能嗎 ?

您可以將populate方法與嵌套語法一起使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM