【问题标题】:Mongodb how to enforce a unique db reference id?Mongodb如何强制执行唯一的数据库参考ID?
【发布时间】: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 字段都是唯一的?

【问题讨论】:

标签: mongodb mongoose mongoose-schema


【解决方案1】:

您应该构建一个unique index,然后在插入/更新具有重复userWhoLiked 值的文档的情况下,您将收到重复键错误。

【讨论】:

  • 在您创建第一个文档之后,您在什么时候致电db.myCollection.createIndex()?是以前吗?我发现文档有点难以理解。我应该在代码中的什么位置放置 createIndex 命令?
  • 你只做一次,所以你真的不需要将它合并到你的代码中。只需运行一次
  • 你分享的参考对我很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
相关资源
最近更新 更多