问题
I need to update a document using mongoose which contains an array of objects where each object within the array also contains an array of objects.
Pseudo code for this would be something like:
user.rooms[{where roomname = 'abc123'}].messages.push({message: 'hello', from: 'james'})
Where 'rooms' is an array of objects.
And 'messages' is an array of objects which sits inside a room object which itself sits in the rooms array.
I am confused as to how to build the query in terms of using $ in mongoose for arrays as well as $elemMatch. dot syntax, $set versus $push etc...
var roomname = 'abc123';
User.findOneAndUpdate({'rooms.name' : room},{ */* WHAT GOES HERE? */* }, {upsert:true} function (err, messagesDoc) {
if (err){
return done(err);
}
if (messagesDoc) {
} else {
}
});
Is this possible? Should I have gone with a separate collections for users and rooms instead?
EDIT / UPDATE
So I have been trying to figure this out and think I am getting closer but I am now getting an error.
This is the query I am using now:
User.findOneAndUpdate({ 'local.rooms.name' : room },
{$push: {'local.rooms.$.messages': chatmessage}},
function(err, doc) {
});
This is the error I am getting:
C:\[PATH]\app\node_modules\mongoose\node_modules\mquery\lib\utils.js:
26
if (/ObjectI[dD]$/.test(obj.constructor.name)) {
^
RangeError: Maximum call stack size exceeded
DEBUG: Program node app exited with code 8
I should also add that I can see the first part of the query is working. If I cnange it to find one I can log out the extpected results. It seems to be the update object that is causing the error.
回答1:
It appears that you can't seem to store a mongoose model using the findOneAndUpdate and using $push to push the model object into the database. When I changed this to $push an object I created with the same properties as the model (without the auto generated id of course) the object would be inserted into the database just fine.
I am unsure if this is a bug or intended functionality.
My actual solution was to restructure the database so I no longer have nested subdocuments as object arrays. i.e. I created a new collection for rooms. I also went with the findOne() function then use the save() function rather than findOneAndUpdate(). This lets me store the mongoose model without any problems.
来源:https://stackoverflow.com/questions/22879616/nodejs-and-mongoose-querying-and-updating-object-arrays-inside-object-arrays