简体   繁体   中英

Update data in MongoDB with Mongojs using findAndModify()

Yet another first-timer problem here. This gets data from a database and displays it in some text fields (that part is not shown in the code below) and after the user edits it the data should be updated in the database via the findAndModify() method and I think this is where the issue lies. There are no errors, it just doesn't do anything. EDIT The following error is received: MongoError: Either an update or remove=true must be specified

server.js

MongoClient.connect("mongodb://user:secretPassword@aws-us-east-1-portal.7.dblayer.com:10712,aws-us-east-1-portal.10.dblayer.com:10316/database", function(err, db) {
    if (err) throw err;
    var contactList = db.collection("contactList");

app.put('/contactList/:id', function(req, res) {
    var id = req.params.id;
    console.log("edited: " + req.body.name); //works up until here
    contactList.findAndModify({
        query: {_id: mongojs.ObjectId(id)},
        update: {$set: {name: req.body.name, email: req.body.email, number: req.body.number}},
        new: true
    }, function (err, doc) {
        res.json(doc);
    })
});

controller.js

$scope.update = function() {
    $http.put('/contactList/' + $scope.contact._id, $scope.contact).success(function(response) {
        refresh();
    })
};

If this were me I would first do a couple of things:

  1. Before your call to findAndModify just do a simple find using your query. Make sure you can actually find the object using your query. If that works you know that the 'find' part of the findAndModify is probably ok.

  2. Do some console logging inside the callback handler of the findAndModify call. As it stands you do not do anything if an err is returned from the findAndModify call. It is possible your call is returning an error that you are just ignoring and it may provide some additional insight into your problem.

I would try these two first and see if it helps.

Update:

Example using native:

collection.findAndModify(
     { field: 'some value' }, 
     [], 
     { $set: { field2: 'some new value' } }, 
     { new:true }, 
     function(err, doc) {
        //handle err and doc
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM