Node.js 如何将mongoose字段的默认值设置为现有条目数?

Node.js 如何将mongoose字段的默认值设置为现有条目数?,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我试图将mongoose模式中字段的默认值设置为数据库中已经存在的条目数 要创建的第一个条目将具有该字段的值0,第二个条目应具有值1等 Background:它应该是某种排序索引,用户可以更改,但默认为条目的创建顺序。因此,它应该是唯一的序列号 到目前为止,我的猫鼬模式是这样的: const CategorySchema = Schema({ title: String, sorting: { type: Number, index: { unique: true }, default:

我试图将mongoose模式中字段的默认值设置为数据库中已经存在的条目数

要创建的第一个条目将具有该字段的值
0
,第二个条目应具有值
1

Background:它应该是某种排序索引,用户可以更改,但默认为条目的创建顺序。因此,它应该是唯一的序列号

到目前为止,我的猫鼬模式是这样的:

const CategorySchema = Schema({
  title: String,
  sorting: { type: Number, index: { unique: true }, default: ##number_of_existing_entries### },
  creationDate: { type: Date, default: Date.now },
});

const Category = mongoose.model('Category', CategorySchema);

有谁能帮我实现期望的行为吗?

我知道这是一个老问题,但如果你像我一样在谷歌上找到它

解决方案的一半:

const CategorySchema = Schema({
    title: String,
    sorting: { 
        type: Number, 
        index: { unique: true }, 
        default: function() {
            const collection = this.parent().categories;
            return (collection) ? collection.length : 0;
        }
    },
    creationDate: { type: Date, default: Date.now },
});

const Category = mongoose.model('Category', CategorySchema);

另一半是自动获取集合名称

您不能像Mongoose本身那样在ORM级别执行此类操作,但您可以做的是改进JavaScript中的此功能level@FelixFong:当然,这是解决办法。