Markuz Shultz
Markuz Shultz

Reputation: 678

MongoDB insert record issue

I have a Mongo DB structure which looks something like this :

db.users.find().pretty();
{
    "_id" : ObjectId("52b42b148ffa91f7ebbe8ebc"),
    "username" : "test",
    "password" : "test",
    "party" : [
        "4988",
        "5037"
    ],
    "something" : [
        "3571"
    ],
    "ludilo" : [],


}

Im using express js in my app and this module for connecting to Mongo https://npmjs.org/package/mongodb ,

How can I insert one entry into "something" array for user with id that I get from session.

I tried something like this , but with no success

var collection = db.collection('users');
         collection.find({'_id':new ObjectID(req.user.id)}).toArray(function(err, items) {
            console.dir(items);
          }).insert({"something":"1234"});

Upvotes: 0

Views: 89

Answers (2)

Oleg
Oleg

Reputation: 23277

You can try this code:

collection.find({_id: new ObjectID(req.user.id)}).toArray(function(err, items) {
  var doc = items[0];
  doc.something.push('1234');
  collection.update({_id: doc._id}, {$set: {something: doc.something}}, {safe: true}, function() {
    //your next actions
  });
});

I run this code on my local machine and it seems to work fine

Upvotes: 0

heinob
heinob

Reputation: 19464

You can $push a value to an array with

db.users.update(
    { _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
    { $push: { something: "1234" } }
)

or if you do not want any duplicates in your array you can use $addToSet

db.users.update(
    { _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
    { $addToSet: { something: "1234" } }
)

Upvotes: 2

Related Questions