首页 > 解决方案 > 具有自动文档计数的 Mongoose 字段

问题描述

我正在尝试创建一个 Mongoose 模式,其中包含一个按以下格式自动递增的字段:number-year. 因此,例如,如果我今年(2018 年)创建了 3 个文档,他们应该在该字段中包含以下值:1-2018, 2-2018, 3-2018, ...

我正在使用该函数estimatedDocumentCount来计算集合中的文档数。这是我的代码示例:

var db = mongoose.connection;

var FooSchema = new mongoose.Schema({
    code: {
        type: String,
        index: true,
        match: /\d{1,}-\d{4}/,  // Code is in format nr-yyyy
        default: function() {
            return Foo.estimatedDocumentCount({})
                .then(count => `${count}-${(new Date()).getFullYear()}`)
                .catch(error => console.error(error))
        }
    }
});
var Foo = module.exports = mongoose.model('Foo', FooSchema);

不幸的是,我收到以下错误:

TypeError: Foo.estimatedDocumentCount is not a function

这是package.json

"mongodb": "^2.2.33",
"mongoose": "^4.13.2",

先感谢您。

标签: mongodbmongoosemongoose-schema

解决方案


推荐阅读