实际上有2个问题,让我逐个回答。
Mongoose 正在创建此 ID,还是由 MongoDB 创建?
更准确的答案是MongoDB Node.js 驱动程序(不是 MongoDB 服务器)
Let's make a clear distinction about what we are referring to:
Please note from the reference
MongoDB driver automatically generates an ObjectId for the _id field
...
MongoDB clients should add an _id field with a unique ObjectId.
The _id field is generated at the client side, unlike some databases that have the functionality to generate the primary field at the database server.
What actually happens is that Mongoose calls the ObjectId function that is provided by the MongoDB native driver. This is done without the server, i.e. you can generate an ObjectId without a server connection. You can try the following code:
/* no any database connection logic */
const TestSchema = new mongoose.Schema() // blank schema, should contain only _id field
const Test = mongoose.model('Test', TestSchema)
const test = new Test()
console.log(test.toString()) // this will log an object with an _id field
See output on RunKit
Also, why the strange syntax of an object in an object, why not just put the ID directly as value of _id?
This is just a string representation of the actual 96-bit data. It's an Extended JSON format that is used to represent MongoDB documents as human readable.