简体   繁体   English

Mongoose/Mongodb findOneAndUpdate 同时保留已经存在的内容

[英]Mongoose/Mongodb findOneAndUpdate while keeping what is already there

I'm saving many items per User in my db via mongoose, items end inside item (array) in the User schema.我通过 mongoose 在我的数据库中为每个用户保存了许多项目,项目在User模式中的项目(数组)内结束。 How do I tell mongodb to findOneAndUpdate while keeping the items that are already there ?如何告诉 mongodb findOneAndUpdate同时保留已经存在的项目 Because right now the update basically override the whole item array in the db for that User.因为现在更新基本上覆盖了该用户数据库中的整个项目数组。

What I have is this:我所拥有的是:

            var filter = { 'id': thisId };
            let update = { 
              'item': itemsArray,
              'updatedAt': Date.now()
            };

            User.findOneAndUpdate(filter, update, {upsert: true, new: true}, function(err, doc) {
                if (err) return res.send(500, {error: err});
                return;
            });

I've read about the $addToSet in the mongodb docs, but is it what I need here?我在 mongodb 文档中阅读了有关$addToSet的信息,但这是我需要的吗? How can I apply it to my query?如何将其应用于我的查询?

UPDATE : the $set as suggested below doesn't work.更新:下面建议的$set不起作用。 My example: I fetch 400 items inside the field 'item' , then with a conditional based on last update date, I fetch 50 items the second time, now let's say among these 50 there's one item which is not already present among the 400 previously added, I'm expecting it to add the item to the 400 becoming 401. Instead what happens is i now find 50 items total inside the 'item' field我的示例:我在字段'item'中获取 400 个项目,然后基于上次更新日期的条件,我第二次获取 50 个项目,现在假设在这 50 个项目中,有一个项目在之前的 400 个中不存在补充说,我希望它将项目添加到 400 成为 401。相反,我现在在“项目”字段中找到总共 50 个项目

SOLUTION I FOUND :我找到的解决方案

User.findOneAndUpdate(filter, { $set : {'updatedAt': Date.now()}, $addToSet : {'item': itemsArray} }, {upsert: true}, function(err, doc) {
                    if (err) return res.send(500, {error: err});
                    return;
                });

you should use $push:你应该使用 $push:

var filter = { 'id': thisId };

User.findOneAndUpdate(filter, { 
   $set : { 'updatedAt': Date.now() }, 
   $push : { 'item': itemsArray } 
}, {upsert: true, new: true}, function(err, doc) {
   if (err) return res.send(500, {error: err});
   return;
});

Use $addToSet with $each to update the array and use $set to update the rest of the fields.使用$addToSet$each更新数组,使用$set更新字段的 rest。 This can be done in the same query.这可以在同一个查询中完成。

In this case it will perform the upsert operation since document with name raj in not present.在这种情况下,它将执行 upsert 操作,因为名称为 raj 的文档不存在。


user = { _id: ObjectID("5ff171ce57fd21194c9f0d71"),
  name: 'ankit',
  item: [ 'apple', 'orange' ] }

db.user.findOneAndUpdate({name:'raj'},{$set:{age:13},$addToSet:{item:{$each:['apple','banana']}}},{upsert:true,new:true})

Here it will simply update the fields including the array field.在这里,它将简单地更新包括数组字段在内的字段。


user = { _id: ObjectID("5ff171ce57fd21194c9f0d71"),
  name: 'ankit',
  item: [ 'apple', 'orange' ] }

db.user.findOneAndUpdate({name:'ankit'},{$set:{age:1},$addToSet:{item:{$each:['apple','banana']}}},{upsert:true,new:true})

I think it's not best using the findOneAndUpdate() try this:我认为最好不要使用findOneAndUpdate()试试这个:

const filter = { 'id': thisId };
const user = await User.findOne(filter);
user.items.push(...itemsArray) // If itemsArray is an array
await user.save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM