【发布时间】:2020-03-12 00:39:38
【问题描述】:
Mongodb 如何强制执行唯一的数据库引用 id?
const LikeSchema = new mongoose.Schema({
idOfPost: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
required: true,
},
userWhoLiked: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
unique: true // This is not working? Why?
},
date=:{
default: Date.now,
required: true,
type: Date,
},
如何确保所有 userWhoLiked 字段都是唯一的?
【问题讨论】:
-
如果你的“AutoIndex”是“off”,你需要明确地调用mongoosejs.com/docs/api.html#model_Model.ensureIndexes。如果您有违反唯一性的文档,则不会创建索引。
标签: mongodb mongoose mongoose-schema