Home How to define PUT method for complex json objects for updating records in mongoDB using nodejs scripts?
Reply: 1

How to define PUT method for complex json objects for updating records in mongoDB using nodejs scripts?

CodeHunter
1#
CodeHunter Published in 2018-02-14 07:10:12Z

I want to define a put method by using findOneAndUpdate() on a mongoDB object using AngularJS. I am able to successfully do GET and POST operations but I am having difficulty defining PUT. Below is my db object defined in app.js file:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testing23');

    var idObj = Schema({

        _id: String,
        name : {
            firstname : String,
            lastname : String
        },
        phones : [Number],
        emails : [String],
        friends : [String]

    });
var Error = mongoose.model('Error', idObj );

My GET and POST are below:

app.get('/api/info',function(req,res){
    Error.find(function(err,infos){
        if(err)
            return res.send(err);
        return res.json(infos);
    });
});
app.post('/api/info',function(req,res){
    Error.create(req.body, function(err,infos){
        if(err)
            return res.send(err);
        return res.json(infos);
    });
});

For PUT I am using below method but it is not working:

app.put('/api/infos/:id',function(req,res){

    Error.findOneAndUpdate({_id: req.params.id},req.body,function(err,infos){
        if(err)
            return res.send(err);
        return res.json(infos);
    });
});

How can I successfully do a PUT operation?

Enda Molloy
2#
Enda Molloy Reply to 2018-02-14 08:25:40Z

As per the Mongoose Docs your find and modify command should look like the following

Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)

For the example you provided and say you want to update the name, it would be

Error.findOneAndUpdate({_id: req.params.id},{ $set: { name: req.body }},{new: true},function(err,updatedInfos){
        if(err)
            return res.send(err);
        return res.json(updatedInfos);
    });

Using {new:true} means the updated document gets returned.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30207 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO