【问题标题】:Mongoose ODM saves wrong model name in MongoDB collectionMongoose ODM 在 MongoDB 集合中保存了错误的模型名称
【发布时间】:2019-08-23 01:36:59
【问题描述】:

你好 Stackoverflowers!

Mongoose 创建名为“Safes”的集合时遇到了一个奇怪的问题。

这是我的示例代码:

const mongoose = require('mongoose')
mongoose.connect('mongodb://mongodb:27017/test', { useNewUrlParser: true })

const Safe = mongoose.model('Safe', { name: String })

const safe = new Safe({ name: 'foobar' })
safe.save().then(() => console.log('done'))

当我打开数据库外壳并发出以下命令时:

mongo test --eval "db.getCollectionNames()"

它的响应是:

MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f9cfa8b9-58e2-40b8-9907-ecd18039935a") }
MongoDB server version: 4.0.6
[ "saves" ]

现在,我尝试创建一个集合名称为“Safes”的模型,而 mongoose 似乎将其更改为 safes > saves ...

mongoose 是否有某种无法使用的受保护模型?

【问题讨论】:

    标签: javascript node.js mongoose odm


    【解决方案1】:

    似乎他们为以“fe”结尾的单词设置了规则,因为它们通常会转换为复数形式为“ves”(刀 -> 刀)。

    您可以通过向 Schema 添加另一个参数来设置自己的集合名称:

    const safeSchema = new Schema({ name: String }, { collection: 'safes' })
    

    【讨论】:

    • 这是解决方案...谢谢! :D
    【解决方案2】:

    Mongooses util.toCollectionName 根据 Schema 名称生成集合的名称。它确实使用了一些正则表达式,其中之一是:

      [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
    

    这很安全fe 并将其替换为 saves

    source

    【讨论】:

    • 也谢谢你,现在我知道正则表达式可能会因为某些单词而失败! ;D
    猜你喜欢
    • 2014-09-22
    • 2013-06-24
    • 1970-01-01
    • 2014-09-21
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多