如何在猫鼬中插入带有 collection.insert() 的自定义 ObjectId

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

我正在尝试将多个用户批量插入到数据库中。出于测试目的,我想为每个单独的文档设置一个特定的 ObjectId。出于某种原因,我无法插入有效的 ObjectId。

例如:

    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")
    }
});

...在 mongoDB 中插入:

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

当我尝试查询具有指定 _id 的文档时,这会导致各种问题。 我的原始代码工作正常,但缺少不错的多插入选项:

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();
    })
});

在 mongoDB 中插入:

ObjectId("56955ca46063c5600627f393")

有没有办法使用有效的 ObjectId 在数据库中插入多个文档?

根据文档 Object in Mongoose and ObjectId in Mongo Shell,您应该执行如下操作:

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")
    }
});

如果您正在使用 MongoDB CLI,那么您可以像这样使用 insertMany()

db.User.insertMany([
  {
    _id: ObjectId("56955ca46063c5600627f393"),
    name: "John"
  },
  {
    _id: ObjectId("56955ca46063c5600627f392"),
    name: "Doe"
  }
])