猫鼬集合命名错误? [英] Mongoose collection naming bug?

查看:86
本文介绍了猫鼬集合命名错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在猫鼬3.8.12中发现了这种(我认为吗?)不良行为,默认情况下,当您创建一个新的猫鼬模型时,它的名称将复数形式添加一个"s",这是非常正常的,而该模型的名称已经以一个"s",然后按原样保存(预期行为).问题是,当您有两个具有相同名称,一个复数和另一个单数的不同模型时,猫鼬允许您两个创建两个模型,但是在mongo中使用相同的集合来存储两个模型.

假设我有一个名为"car"的收藏集:

mongoose.model('Car', schema);

和汽车"收藏集:

mongoose.model('Cars', schema);

两者都在mongo中保存为汽车"

我不认为这是预期的行为.

解决方案

http://mongoosejs.com/docs/api.html#index_Mongoose-model

当没有传递任何集合参数时,Mongoose通过将模型名称传递给utils.toCollectionName方法来产生一个集合名称.此方法将名称复数.如果您不喜欢这种行为,请传递一个集合名称或设置您的模式集合名称选项.

由于Car变成Cars,并且Cars已经是复数,所以您最终使用了相同的集合名称.模型通常使用单数名称.上面的链接列出了几种设置自定义集合名称的方法.

当然,您总是可以在项目的 GitHub存储库上创建新期刊. /p>

I found this (I think?) undesirable behavior in mongoose 3.8.12, when you create a new mongoose model by default it makes its name plural adding an 's' which is perfectly normal, when the model's name already ends with an 's' then save it as it is (expected behavior). The problem is when you have two different models with the same name but one plural and the other singular, then mongoose allows you two create the two but uses the same collection in mongo to store both.

let's say I have a collection named 'car':

mongoose.model('Car', schema);

and a collection 'cars':

mongoose.model('Cars', schema);

both are saved in mongo as 'cars'

I don't think that is the expected behavior.

解决方案

http://mongoosejs.com/docs/api.html#index_Mongoose-model

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

Since Car turns into Cars, and Cars is already plural you end up with the same collection name. Models are generally given the singular name. The link above lists several methods to set a custom collection name.

Of course, you can always create a new issue on the project's GitHub repo.

这篇关于猫鼬集合命名错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆