How to define a shared nested object in Mongoose

I would like to have a nested object in the details for activiy magazine. See an example. How to determine the pattern in 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' } 
+8
mongodb mongoose
source share
2 answers

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

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

To specify an arbitrary object (ie, "everything goes") in your schema, you can use the Mixed type or just {} .

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

Trap

However, for added flexibility, there is a catch. When using Mixed (or {} ), you need to explicitly tell mongoose that you made such changes:

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

A source

+7
source share

All Articles