如何使变量成为猫鼬的唯一键?
问题描述:
例如,如果我有此架构
var userSchema = mongoose.Schema({
username: String,
email: String,
password: String,
_todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});
我希望用户名是唯一密钥,其他用户不能重复.我该怎么办?
I would like the username to be a unique key that cannot be duplicated by other users. How can I do this?
答
您可以使用unique
属性添加约束.这还将为该字段添加一个唯一"索引到您的集合:
You can add a constraint with the unique
attribute. This will also add a "unique" index for the field to your collection:
var userSchema = mongoose.Schema({
username: { type: String, unique: true },
email: String,
password: String,
_todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});