Create new object id in mongoDB using node js

I am using the below code to insert data into mongodb

    router.post('/NewStory', function (req, res) {
var currentObject = { user: userId , story : story , _id:new ObjectID().toHexString() };
        req.db.get('clnTemple').findAndModify({
            query: { _id: req.body.postId },
            update: { $addToSet: { Stories: currentObject } },
            upsert: true
        });
});

      

This code works fine if I remove _id:new ObjectID().toHexString()

What I want to achieve here is that for every new story I want to add a unique _id object to it

What am I doing wrong?

{
    "_id": {
        "$oid": "55ae24016fb73f6ac7c2d640"
    },
    "Name": "some name",
     ...... some other details
    "Stories": [
        {
            "userId": "105304831528398207103",
            "story": "some story"
        },
        {
            "userId": "105304831528398207103",
            "story": "some story"
        }
    ]
}

      

This is the document model, _id I am trying to create, for stories

+3


source to share


2 answers


You don't have to call .toHexString()

on this, since you will get a "string" and not an ObjectID. The string takes up more space than bytes ObjectId

.

var async = require('async'),
    mongo = require('mongodb'),
    db = require('monk')('localhost/test'),
    ObjectID = mongo.ObjectID;


var coll = db.get('junk');

var obj = { "_id": new ObjectID(), "name": "Bill" };

coll.findAndModify(
  { "_id": new ObjectID() },
  { "$addToSet": { "stories": obj } },
  {
    "upsert": true,
    "new": true
  },
  function(err,doc) {
    if (err) throw err;
    console.log(doc);
  }
)

      

So this works great for me. Marking also the "new" option, so the modified document is returned, not the original form of the document, which is the default.

 { _id: 55c04b5b52d0ec940694f819,
   stories: [ { _id: 55c04b5b52d0ec940694f818, name: 'Bill' } ] }

      



However, there is a catch, and if you use and generate a new one for each element, then the new one makes everything "unique". So you keep adding things to the "set". It can be , if that's what you want to do. $addToSet

ObjectId

ObjectId

$push

So, if userId

and story

in combination already makes it "unique" then do this:

coll.findAndModify(
  { 
      "_id": docId, 
      "stories": {
          "$not": { "$elemMatch": { "userId": userId, "story": story } }
      }
  },
  { "$push": { 
     "stories": {
         "userId": userId, "story": story, "_id": new ObjectID()
     }
  }},
  {
    "new": true
  },
  function(err,doc) {
    if (err) throw err;
    console.log(doc);
  }
)

      

So, check for unique elements in the array and where they don't exist add them to the array. Also noting that you cannot perform "inequality matching" on an array element when mixed with "upserts". Your test to "update" the document should only be on the primary "_id" value. Array entries and upserts must be managed in separate update operations. Don't try to mix the two, or you will end up creating new documents if you don't intend to.

+3


source


By the way, you can ObjectID

only generate with monk

.



var db = monk(credentials.database);

var ObjectID = db.helper.id.ObjectID

console.log(ObjectID()) // generates an ObjectID

      

+3


source







All Articles