node.js - 不存在则插入,存在则更新

标签 node.js mongodb

<分区>

我正在从这个 API 获取用户。

https://redmine-mock-api.herokuapp.com/api/v1/users

一共有100个(100个不同的id)。我使用 Mongoose 将它们添加到我的 mongodb 数据库中,但问题是它总是在添加(我已经有 5000 个用户(50 次重复 100 个用户)

如果 id 不存在我想添加,如果存在则更新。

我做错了什么? users 是 API 中的用户数组

 db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });

最佳答案

试试下面的格式

db.collection.update({'_id': Id}, //Find with the unique identifier
                     {//put whatever you want to insert},
                     {upsert: true}
                    )

关于node.js - 不存在则插入,存在则更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56395441/

相关文章:

mongodb - 如何使用吗啡在复合键上注释索引

嵌套数组上的 MongoDB $elemMatch 投影

node.js - 为什么我不能使用 node-postgres 从数据库中删除?

javascript - 通过增加 javascript 中的数字使记录唯一

c++ define指令失败,代码看起来不错

javascript - express js如何将数组转换为对象

mongodb - 将数据保存在 mongodb docker 容器的外部文件夹中

node.js - npm `wanted` 与 `latest`

javascript - NodeJS - FormData 向服务器发送未定义的值

node.js - 如何检查redis中是否已存在 session ID