【问题标题】:mongoose populate a filed in a subdocument array [duplicate]猫鼬填充子文档数组中的字段[重复]
【发布时间】:2015-09-29 15:03:54
【问题描述】:

使用猫鼬,我想在我的主文档的子文档数组中填充一个属性。这是一个例子:

var Question = new Schema({
  title: {type: String},
  answers: Schema.Types.Mixed, //{A:'',B:''}
  category: {type: String}, 
  type: {type: String},        
  enable: {type: Boolean, default: true},
  sex: Number,             
  //random: {type: Number, default: Math.random}, 
  createdAt: {type: Date, default: Date.now} 
});

var User = new Schema({
  username: {type: String},    
  password: {type: String},
  typeQuestion: [{q: {type: Schema.Types.ObjectId, ref: 'Question'}, a: String,option:String }],    
});

如何从 User 中填充 typeQuestion,谁能告诉我怎么做?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    很简单:

    User.find({})
        .populate('typeQuestion.q')
        .exec(function(err, user) {
            // callback
        });
    

    您可以通过简单地引用该项并“忽略”数组来填充数组中的项。

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2017-05-07
      • 2021-02-11
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2015-07-28
      • 2016-05-16
      相关资源
      最近更新 更多