7

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?

Eric Kigathi
  • 1,815
  • 21
  • 23
stephan
  • 655
  • 1
  • 7
  • 11

2 Answers2

10

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")
    }
});
Rogier Spieker
  • 4,087
  • 2
  • 22
  • 25
3

If you are using MongoDB CLI then you can use insertMany() like this

db.User.insertMany([
  {
    _id: ObjectId("56955ca46063c5600627f393"),
    name: "John"
  },
  {
    _id: ObjectId("56955ca46063c5600627f392"),
    name: "Doe"
  }
])
Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97