【问题标题】:MongoDB update many if exist and create if not. Node APIMongoDB 如果存在则更新很多,如果不存在则创建。节点 API
【发布时间】:2017-08-30 07:23:09
【问题描述】:

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

我有发布功能,但我需要更多功能。 现在我使用 Postman 发送数据,我的发布请求如下所示:

[
  { "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)不存在我想根据这个创建用户架构:

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 更新了一个用户,但我正在发送元素数组,我不知道如何处理多个元素。

谢谢

【问题讨论】:

标签: json node.js mongodb rest


【解决方案1】:

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

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

// 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!' });
});

【讨论】:

  • 谢谢。像魅力一样工作。
猜你喜欢
  • 2021-06-13
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 2012-12-17
相关资源
最近更新 更多