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?
Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it. In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
You either need to declare the _id property as part of your schema (you commented it out), or use the _id option and set it to false (you're using the id option, which creates a virtual getter to cast _id to a string but still created an _id ObjectID property, hence the casting error you get).
insert() method is used to insert a new document in a collection. A document or array of documents to insert into the collection.
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")
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With