0

我有我使用的简单代码如下:

// mongoose helper methods
const saveInstance = (name, schema, obj) => {
  const Model = mongoose.model(name, schema);
  const Instance = new Model(obj);
  return Instance.save();  
};

该架构没有 ID 属性,但我在数据库中看到了这个:

"_id": {
        "$oid": "5c14201afbf31900047f9ccf"
    },

我想假设 Mongoose 正在创建这个 ID,还是 MongoDB 创建了这个?你能提供一个参考吗?

另外,为什么对象中对象的语法很奇怪,为什么不直接将 ID 作为值_id呢?

4

2 回答 2

1

MongoDB 博客文章:

默认情况下,MongoDB 在将该文档写入数据库之前生成一个唯一的 ObjectID 标识符,该标识符分配给新文档中的 _id 字段。

邮政

于 2020-05-19T18:26:42.303 回答
1

实际上有2个问题,让我逐个回答。

  1. 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

  1. 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.

于 2020-05-19T21:18:23.080 回答