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?
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'
}
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
})
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
});
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:
activity.detail.title = "title";
activity.markModified('detail');
activity.save();