Model.save() doesn't save embedded arrays
See original GitHub issueI have nested arrays of documents, and when I change them and do a .save() on the model it does not save the changes in the nested document.
Here are my models and schemas (some ommited for brevity):
var Votes = new mongoose.Schema({
date: Date,
user_name: String,
is_up: Boolean
});
var EventSchema = new mongoose.Schema({
to_date: Date,
from_date: Date,
location: String,
name: String,
suggested_by: String,
description: String,
users: [EventUser],
comments: [Comments],
suggestions: [Event],
votes: [Votes]
});
var Event = mongoose.model('Event', EventSchema);
Model before event.save() called:
{
__v: 1,
_id: 509e87e583ccbfa00e000004,
description: 'Pfft',
from_date: Sun Nov 11 2012 08:00:00 GMT-0500 (EST),
location: 'Home',
name: 'Whatever',
suggested_by: 'No one',
to_date: Sun Nov 11 2012 00:00:00 GMT-0500 (EST),
votes: [],
suggestions:
[ { users: [],
comments: [],
suggestions: [],
votes: [],
_id: 509e880883ccbfa00e000005,
suggested_by: 'Some one',
to_date: Sun Nov 11 2012 04:00:00 GMT-0500 (EST),
from_date: Mon Nov 12 2012 00:00:00 GMT-0500 (EST),
location: 'Home',
name: 'Football',
description: 'FOOTBALL!!' } ],
comments: [],
users: []
}
The same object with the nested votes right before event.save()
is called.
{
"__v":1,
"_id":"509e87e583ccbfa00e000004",
"description":"Pfft",
"from_date":"2012-11-11T13:00:00.000Z",
"location":"Home",
"name":"Whatever",
"suggested_by":"No one",
"to_date":"2012-11-11T05:00:00.000Z",
"votes":[ ],
"suggestions":
[ {
"users":[],
"comments":[ ],
"suggestions":[ ],
"votes":
[{
"is_up":true,
"date":"2012-11-10T18:05:25.796Z",
"user_name":"No one"
}],
"_id":"509e880883ccbfa00e000005",
"suggested_by":"Some one",
"to_date":"2012-11-11T09:00:00.000Z",
"from_date":"2012-11-12T05:00:00.000Z",
"location":"Home",
"name":"Football",
"description":"FOOTBALL!!"
}],
"comments":[],
"users":[]
}
When event.save() is called, no error is thrown, but the nested votes schema inside of the nested events schema is not actually saved. If I use the same overall logic in the top level event object to save a vote, it does work.
When I looked through the code, briefly, it appears that .save() is suppose to be a shortcut for both saving new objects, as well as updating ones that already exist.
My hunch is Model.prototype._delta isn’t going deep enough to catch all nested objects, https://github.com/LearnBoost/mongoose/blob/master/lib/model.js#L529
Issue Analytics
- State:
- Created 11 years ago
- Comments:26
Top GitHub Comments
Thanks, it was this issue in my case ! 😃
model.myArray[index] = anyValue
becomes
model.myArray.set(index, anyValue)
I see what the issue is - classic case of the first question on the mongoose FAQ. Mongoose can’t track changes when you set an array index directly without something like ES6 proxies or ES7
Object.observe()
. Useor