0

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

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}
]

And this is my post function:

.post(function(req, res) {

    User.insertMany(req.body)

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

})

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);

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.

Thank you

omygoodness
  • 335
  • 3
  • 18
  • 1
    Possible duplicate of [Bulk upsert in MongoDB using mongoose](http://stackoverflow.com/questions/25285232/bulk-upsert-in-mongodb-using-mongoose) – Alex Blex Apr 04 '17 at 21:58

1 Answers1

0

You could iterate and do one operation at a time.

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!' });
});
Mikey
  • 6,728
  • 4
  • 22
  • 45