问题描述
我需要使用 mongoose 更新一个包含对象数组的文档,其中数组中的每个对象也包含一个对象数组.
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.
这个的伪代码类似于:
user.rooms[{where roomname = 'abc123'}].messages.push({message: 'hello', from: 'james'})
其中房间"是一组对象.
Where 'rooms' is an array of objects.
'messages' 是一个对象数组,它位于一个房间对象内,房间对象本身位于房间数组中.
And 'messages' is an array of objects which sits inside a room object which itself sits in the rooms array.
我很困惑如何根据在 mongoose 中将 $ 用于数组以及 $elemMatch 来构建查询.点语法,$set 与 $push 等...
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?
编辑/更新
所以我一直在尝试解决这个问题,并认为我越来越接近了,但我现在遇到了一个错误.
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) {
});
这是我得到的错误:
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.
推荐答案
看来您似乎无法使用 findOneAndUpdate 并使用 $push 将模型对象推送到数据库中来存储 mongoose 模型.当我将其更改为 $push 时,我创建的对象具有与模型相同的属性(当然没有自动生成的 id),该对象将被插入到数据库中就好了.
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.
我的实际解决方案是重构数据库,这样我就不再将嵌套子文档作为对象数组.即我为房间创建了一个新集合.我还使用了 findOne() 函数,然后使用了 save() 函数而不是 findOneAndUpdate().这让我可以毫无问题地存储猫鼬模型.
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.
这篇关于Nodejs 和猫鼬.查询和更新对象数组内的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!