findOneAndUpdate导致重复问题 [英] findOneAndUpdate causing duplication problem

查看:94
本文介绍了findOneAndUpdate导致重复问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在猫鼬的findOneAndUpdate中遇到问题.情况是我正在通过查找来更新文档.查询如下:

I am having a problem in findOneAndUpdate in mongoose. The case is that i am updating a document by finding it. The query is as follows:

UserModel.findOneAndUpdate({
individualId: 'some id'
}, {
$push: {
supporterOf: 'some string'
}
})

'supporterOf'是UserModel的引用,其类型为'ObjectId'.

The 'supporterOf' is the ref of UserModel and its type is 'ObjectId'.

我在这里面临的问题是,某些字符串"在文档的"supporterOf"下被两次推送.

The issue i am facing here is that, 'some string' is being pushed twice under 'supporterOf' in the document.

谁能告诉我如何在文档中推送数组元素?

Can anyone tell me that how to push an array element inside the document?

推荐答案

我最近遇到了同样的问题.但是,我设法通过其他一些逻辑(下面给出了详细信息)解决了这个问题,但是不明白为什么 findOneAndUpdate 在mongodb中插入 duplicate 条目的原因.

I have recently encountered the same problem. However, I managed to overcome this issue by some other logics (details given below) but couldn't understand the reason behind that why findOneAndUpdate inserting duplicate entries in mongodb.

您可以通过遵循以下逻辑来克服此问题.

You can overcome this problem by following logic.

使用 findOne findById 代替 findOneAndUpdate 来搜索集合中的文档,然后手动更新文档并运行 save().

Use findOne or findById instead of findOneAndUpdate to search the document in your collection and then manually update your document and run save().

您可以使用此代码段

return new Promise(function (resolve, reject) {
    Model.findOne({
            someCondition...
        }, function (err, item) {
            if (err) {
                reject(err);
            } else {
                item.someArray.push({
                    someKeyValue...
                });
                item.save().then((result) => {
                    resolve(result)
                }).catch((err) => {
                    reject(err)
                });
            }
        }).catch((err) => {
            reject(err)
        });
   });

这不会插入重复的项目.但是,如果您知道重复的原因,则必须更新此线程.

This will not insert duplicate item. However, if you come to know the reasoning behind duplication, must do update this thread.

这篇关于findOneAndUpdate导致重复问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆