【问题标题】:Mongoose - How to add extra key to ObjectId referred array?Mongoose - 如何向 ObjectId 引用的数组添加额外的键?
【发布时间】:2017-02-08 03:24:02
【问题描述】:
var conversationSchema = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    recipients: [{ type: Schema.ObjectId, ref: 'User' }],
    messages: [ conversationMessageSchema ]
});
mongoose.model('Conversation', conversationSchema);

在上面的示例中,您将如何在收件人数组中添加额外的属性,例如...状态?

I.E.收件人:

[{ _id: { 
    type: Schema.ObjectId, 
    ref: 'User'
  }, 
  status { 
    type: String
  } 
}]

像这样^?

谢谢

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    你可以这样做

     var conversationSchema = new Schema({
        created: { type: Date, default: Date.now },
        updated: { type: Date, default: Date.now },
        recipients: [
          name:{ type: Schema.Types.ObjectId,  ref: 'User' },
          status { type: String}
        ],
        messages: [ conversationMessageSchema ]
    });
    mongoose.model('Conversation', conversationSchema);
    

    【讨论】:

    • 谢谢!除了我可能会将“名称”更改为“收件人”,以免混淆某人,因为该密钥在技术上应该是指一个包含特定收件人信息的对象。
    • 在你成功之前它不会起作用:收件人:[ { name:{ type: Schema.Types.ObjectId, ref: 'User' }, status { type: String}} ],跨度>
    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2013-07-20
    • 1970-01-01
    • 2013-11-01
    • 2022-08-18
    相关资源
    最近更新 更多