How to insert a custom ObjectId with collection.insert() in mongoose

stephan picture stephan · Jan 26, 2016 · Viewed 10.2k times · Source

I'm trying to batch insert several users into the database. For testing purposes I would like to set a specific ObjectId to each individual document. For some reason I can't insert a valid ObjectId.

For example:

    var users = [
    {
        "_id": "56955ca46063c5600627f393",
        "name": "John"
    },
    {
        "_id": "56955ca46063c5600627f392",
        "name": "Doe"
    }
];

User.collection.insert(users, function(err, docs) {
    if (err) {
        console.log("Error");
    } else {
        console.log("Succes")
    }
});

...inserts in the mongoDB:

"_id" : "56955ca46063c5600627f393" //NOT ObjectId("56955ca46063c5600627f393")

This causes all sorts of problems when I try to query for a document with the specified _id. My original code works just fine but lacks the nice multi insert option:

var user1 = new User({
    "_id": "56955ca46063c5600627f393",
    "name": "John"
});

var user2 = new User({
    "_id": "56955ca46063c5600627f392",
    "name": "Doe"
});

user1.save(function(err, response){
    user2.save(function(err, response){
        if (err) console.log(err);
        else  console.log("ok");
        done();
    })
});

inserts in mongoDB:

ObjectId("56955ca46063c5600627f393")

Is there a way to insert multiple documents in the database with a valid ObjectId?

Answer

Rogier Spieker picture Rogier Spieker · Jan 26, 2016

As per documentation Object in Mongoose and ObjectId in Mongo Shell, you should do something like:

var ObjectId = mongoose.Types.ObjectId,
    users = [
      {
        "_id": new ObjectId("56955ca46063c5600627f393"),
        "name": "John"
      },
      {
        "_id": new ObjectId("56955ca46063c5600627f392"),
        "name": "Doe"
      }
    ];

User.collection.insert(users, function(err, docs) {
    if (err) {
        console.log("Error");
    } else {
        console.log("Succes")
    }
});