Tuesday, 4 April 2017

MongoDB update many if exist and create if not. Node API

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



via omygoodness

No comments:

Post a Comment