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

时间:2021-08-22 18:23:44

I would like to have a nested object in the detail for the activiy log. See the example. How do I define the schema in mongoose?

我想在活动日志的详细信息中有一个嵌套对象。查看示例。如何在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 个解决方案

#1


11  

Use the Mixed type, which allows you to store the arbitrary sub-objects in your example.

使用“混合”类型,它允许您在示例中存储任意子对象。

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

#2


7  

To indicate an arbitrary object (i.e. "anything goes") in your schema you can use the Mixed type or simply {}.

要在模式中指示任意对象(即“任何进展”),您可以使用混合类型或简单地使用{}。

var activity: new Schema({
    date: Date,
    user: String, 
    action: String, 
    detail: Schema.Types.Mixed,
    meta: {}  // equivalent to Schema.Types.Mixed

});

The catch

For the added flexibility there is a catch, however. When using Mixed (or {}), you will need to explicitly tell mongoose that you have made changes like so:

然而,为了增加灵活性,有一个问题。使用Mixed(或{})时,您需要明确告诉mongoose您已经进行了如下更改:

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

Source

#1


11  

Use the Mixed type, which allows you to store the arbitrary sub-objects in your example.

使用“混合”类型,它允许您在示例中存储任意子对象。

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

#2


7  

To indicate an arbitrary object (i.e. "anything goes") in your schema you can use the Mixed type or simply {}.

要在模式中指示任意对象(即“任何进展”),您可以使用混合类型或简单地使用{}。

var activity: new Schema({
    date: Date,
    user: String, 
    action: String, 
    detail: Schema.Types.Mixed,
    meta: {}  // equivalent to Schema.Types.Mixed

});

The catch

For the added flexibility there is a catch, however. When using Mixed (or {}), you will need to explicitly tell mongoose that you have made changes like so:

然而,为了增加灵活性,有一个问题。使用Mixed(或{})时,您需要明确告诉mongoose您已经进行了如下更改:

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

Source