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

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

user1530
1#
user1530 Published in May 25, 2018, 9:00 am

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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO