Mongodb如何强制执行唯一的数据库引用ID?

标签 mongodb mongoose mongoose-schema

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 字段都是唯一的?

最佳答案

您应该构建一个 unique index ,那么在插入/更新具有重复 userWhoLiked 值的文档时,您将抛出重复键错误。

关于Mongodb如何强制执行唯一的数据库引用ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60640628/

相关文章:

ruby - 无法使用种子本地主机 :27017 连接到副本集

mongodb - 如何在 meteor 中使用 mongodb skip() 和 limit()?

node.js - 使用for循环mongoose批量插入文档

node.js - Mongodb计数聚合返回0

node.js - 预填充数据库-nodejs + mongodb

mongodb - 在 Mongo 中是模式还是无模式

node.js - Mongoose 加速多个字段的搜索

windows - 无法在 Windows 上将持久文件夹添加到 bitnami/mongodb

node.js - 如何汇总总计百分比

mongoose-schema - Mongoose Schema 静态与方法