David Michael Harrison
David Michael Harrison

Reputation: 374

Why does this Node+MongoDB update using addToSet fail to update the array

I can't figure this out, I've tried executing the same query using terminal and it was successful. I should note the same query returns one row effected when using MongoHub but after checking the record there is no change. Below is the mongo setup and the action to update.

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
    db = new Db('help', server, {safe: true});

type = 'issues';
id = 2;
body = { comments: '64' };

db.collection(type, function(err, collection) {
       collection.update({id:id}, {$addToSet: body}, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(type);
            }
        });
    });

//Mongo Collection Record
{ "_id" : ObjectId( "511c000d994cde0d02adf1ba" ),
  "comments" : [ 
    1, 
    2, 
    3 ],
  "id" : 2,
  "text" : "This is another issue test",
  "title" : "Another Issue Test" }

Any help is greatly appreciated

Upvotes: 1

Views: 761

Answers (2)

David Michael Harrison
David Michael Harrison

Reputation: 374

turns out I wasn't parsing the variable id as an integer which I was getting from the req.params, I should have included that I was fetching the id from the req.params object.

var id = parseInt(req.params.id);

solved the issue.

Upvotes: 1

shargors
shargors

Reputation: 2157

Seems like there are a few issues in this part

db.collection(type, function(err, collection) {
   collection.update({id:id}, {$addToSet: body}, {safe:true}, 

I don't see where type variable is defined in the first line. That means that the collection was likely not found. But you don't have any error checking for this issue between the two lines.

In the update statement you should have {_id: ObjectId(id)} where id should 511c000d994cde0d02adf1ba for your example.

Those are the issues which seem obvious right off the bat.

Upvotes: 0

Related Questions