Are field level uniqueness constraints still supported in Mongo(ose)?

拟墨画扇 提交于 2019-12-11 06:12:50

问题


It looks like mongoose supported field level uniqueness constraints in earlier versions as follows (seen in 2.7.x here):

var SomeSchema = new Schema ({
  field: {index: {unique: true}} // field level
})

I can't find any reference to it in the 4.4.x docs. Is the preferred way to do this on the schema level now, like so (seen in 4.4.x here):

SomeSchema.index({field: 1}, {unique: true}) // schema level

回答1:


Yes, unique indexes are still supported in Mongoose; see here and here in the current docs.

Examples from the linked docs:

var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }});
var s = new Schema({ name: { type: String, unique: true }});

Schema.path('my.path').index({ unique: true, sparse: true });
Schema.path('name').index({ unique: true });


来源:https://stackoverflow.com/questions/37035258/are-field-level-uniqueness-constraints-still-supported-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!