MongoDB更新许多(如果存在)并创建(如果不存在).节点API [英] MongoDB update many if exist and create if not. Node API

查看:234
本文介绍了MongoDB更新许多(如果存在)并创建(如果不存在).节点API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于express.js构建Node rest API.

I am trying to build Node rest API based on express.js.

我有正在运行的帖子功能,但我还需要其他功能. 现在,我使用Postman发送数据,我的发布请求如下所示:

I have post function which is working but I need something more. For now I send data using Postman and my post request looks like this:

[
  { "id": 1, "name": "test", "points": 1},
  { "id": 2, "name": "test2", "points": 2},
  { "id": 3, "name": "test3", "points": 32},
  { "id": 4, "name": "test4", "points": 423},
  { "id": 5, "name": "test5", "points": 321}
]

这是我的帖子功能:

.post(function(req, res) {

    User.insertMany(req.body)

        .then(function(mongooseDocuments) {
            res.json({ message: 'User created!' });
        })
        .catch(function(err) {
            /* Error handling */
        });

})

但是现在我想为数据库中的用户更新点数,如果id(每个用户都有自己的id,所以我不能使用_id)不存在,我想以此为基础创建用户架构:

But now I would like to update number of points for users who are in the database and if id(each user has its own id so I can't use _id) does not exists I would like to create user based on this schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
id: Number,
name: String,
points: Number
})

module.exports = mongoose.model('User', UserSchema);

我设法使用findOneAndUpdate更新了一个用户,但是我正在发送元素数组,但我不知道该如何处理多个元素.

I managed to update one user using findOneAndUpdate but I am sending array of elements and I have no idea what to do with multiple elements.

谢谢

推荐答案

您可以一次迭代并执行一项操作.

You could iterate and do one operation at a time.

这是使用 async.js 进行迭代的一种解决方案.如果您知道如何使用Promises直接循环,则也可以这样做.

Here is one solution using async.js for iterating. If you know how to directly loop using Promises, you can do that also.

// assuming req.body is an array of all the users

async.eachSeries(req.body, function upsert (obj, done) {
    User.findOneAndUpdate({ id: obj.id }, obj, { upsert: true, new: true }, done);
}, function allDone (err) {
    if (err) return res.json(err);
    res.json({ message: 'Users created!' });
});

这篇关于MongoDB更新许多(如果存在)并创建(如果不存在).节点API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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