mongodb的model名称细节

7次阅读

共计 652 个字符,预计需要花费 2 分钟才能阅读完成。

最近研究 api 设计,顺便研究了下 mongodb,教程没有仔细看过,所以使用过程中也遇到了一些诡异的现象。

比如我使用中发现,我创建的模型名称,在对应数据库的 collections 内的名称不一致。我很纳闷,比如我创建的如下:

const PersonModel = Mongoose.model("person", {
  firstname: String,
  lastname: String
});

当我将一条数据写入后,用工具 Robo 3T 发现,名称居然变成了 people。

后来查了相关资料,原来 mongodb 有自己的一套规则,详细的规则,比如我这条:mongoose/lib/utils.js。当然这个是历史版本的例子了。关于这个现象,最新文档中也指出:

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then Mongoose will create the model for your tickets collection, not your ticket collection.

一般情况他会创建一个复数的 model,这种 person 算特殊的了。所以你写得 model 不一定在查询的时候会一样,即便不一样也不要惊讶哦~

正文完
 0