【发布时间】:2019-02-16 01:37:35
【问题描述】:
我在 NodeJS 中使用 Mongoose 来操作 MongoDB 数据库。我遇到的一个问题是,当我定义一个模式时,我想将该模式中的一个字段设置为唯一的。我按照the instructions of the official document设置了字段,但是没有用。有人知道在定义Schema的时候,如何定义一个字段值是唯一的呢?我使用的Mongoose版本是V5.2.13。
【问题讨论】:
我在 NodeJS 中使用 Mongoose 来操作 MongoDB 数据库。我遇到的一个问题是,当我定义一个模式时,我想将该模式中的一个字段设置为唯一的。我按照the instructions of the official document设置了字段,但是没有用。有人知道在定义Schema的时候,如何定义一个字段值是唯一的呢?我使用的Mongoose版本是V5.2.13。
【问题讨论】:
您只需添加unique: true
例如:
const mySchema = new Schema({
test: {
type: String,
unique: true
}
});
【讨论】: