hussain hussain - 1 month ago 15
Node.js Question

How to update document field in mongodb?

I am new to Mongodb so below code i am trying to update document field

string
i have object recieved in post
req.body
now based on
_id
i want to update
string
field but it is not updating record with below implementation. How can i update record using
_id
? Any better approach to update record in terms of async will be appreciated.

routes.js

var Diagram = require('./diagram');
router.post('/saveUpdateDiagram',function(req,res){
console.log(req.body._id);
Diagram.update(req.body);
});


diagram.js

var diagram = require('./diagram.model');
var mongoose = require('mongoose');

var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
console.log('data in controller', data);
Diagram.update({ $set: { 'string' : data.string } });
}
}
module.exports = Diagram;


data.json

{
_id: "57fe42efc3590c7686bad563"
groups: Array[0]
owner: "sh587"
string: "test string should be updated"
text: "gcs_wf_dit.bpmn"
users: Array[1]

}

Answer

We know that JavaScript is case sensitive language you should use diagram.update not Diagram.update

use `diagram.update({ $set: { 'string' : data.string } });

diagram.js should be

diagram.js

var diagram = require('./diagram.model');
var mongoose = require('mongoose');

var Diagram = {
    index: function(callback) {
        diagram.find({}, function(err, result) {
            if (!err) {
                callback(result);
            }
        });
    },
    update: function(data) {
        console.log('data in controller', data);
        diagram.update({_id: data._id}, { $set: { 'string' : data.string  } });
    }
}
module.exports = Diagram;