如何在Mongoose中定义一个通用的嵌套对象

17

我希望在活动日志的详细信息中拥有一个嵌套对象,就像示例中的一样。我该如何在 mongoose 中定义模式?

activity: {
    date: '1/1/2012' ,
    user: 'benbittly', 
    action: 'newIdea', 
    detail: {
        'title': 'how to nest'
        , 'url': '/path/to/idea'
    }

activity: {
    date: '1/2/2012' ,
    user: 'susyq', 
    action: 'editProfile', 
    detail: {
        'displayName': 'Susan Q'
        , 'profileImageSize': '32'
        , 'profileImage': '/path/to/image'
    }
2个回答

14

使用Mixed类型,它允许在您的示例中存储任意子对象。

var Activity = new Schema({
    date : Date
  , user : String 
  , action : String
  , detail : Mixed
})

1
@RyanM提到的markModified部分怎么样?那总是需要的吗? - lukas_o

14
为了在您的架构中表示任意对象(即“任何内容”),您可以使用Mixed类型或简单地使用{}
var activity: new Schema({
    date: Date,
    user: String, 
    action: String, 
    detail: Schema.Types.Mixed,
    meta: {}  // equivalent to Schema.Types.Mixed

});

注意事项

然而,为了获得更大的灵活性,需要注意一点。当使用Mixed(或{})时,你需要明确地告诉mongoose你已经进行了更改,例如:

activity.detail.title = "title";
activity.markModified('detail');
activity.save();

来源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接