如何在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' } 

使用混合types,它允许你在你的例子中存储任意的子对象。

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

要在模式中指定任意对象(即“任何事情都可以”),您可以使用Mixedtypes或简单地{}

 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(); 

资源

  • mongoose文档