【问题标题】:Mongoose - don't allow documents to have identical arraysMongoose - 不允许文档具有相同的数组
【发布时间】:2017-05-03 05:05:06
【问题描述】:

我想创建一个数据库模式,其中一个文档不能包含与另一个文档相同的数组。所以,假设我有架构 conversations:

var ConversationSchema = new Schema({
    name: String,
    participants: {
        type: [{
            type: Schema.Types.ObjectId,
            ref: 'User'
        }]
    }
});

现在,如果我与相同的参与者创建两个对话,我如何验证这一点,以便第二个失败,而第三个不会?

var conversation1 = new Conversation({
    name: "Hello",
    participants: ['12345', '09876']
});

var conversation2 = new Conversation({
    name: "World",
    participants: ['12345', '09876']
});

var conversation3 = new Conversation({
    name: "Group chat",
    participants: ['12345', '09876', '13579']
});

conversation1.save(); // Valid
conversation2.save(); // Invalid - conversation already exists
conversation3.save(); // Valid

【问题讨论】:

  • 这似乎是业务逻辑而不是模式验证

标签: node.js mongodb mongoose


【解决方案1】:

我猜你可以在保存数据之前使用一些自定义的 Mongoose 验证。 但这并不是真正的架构问题,正如 Kevin 在评论中所说,因为您需要进行数据库查询以将现有数组与新数组进行比较。
像这样的东西(未测试):

function checkArray(arr) {
// here make a call to the db to compare existing array with arr
}

var ConversationSchema = new Schema({
    name: String,
    participants: {
        type: [{
            type: Schema.Types.ObjectId,
            ref: 'User',
            validate: checkArray
        }]
    }
});

暂时没有更好的主意。

【讨论】:

  • 这有点糟糕,但我想我可以这样做。谢谢
猜你喜欢
  • 2020-10-22
  • 2020-10-09
  • 2021-09-30
  • 2020-12-19
  • 2014-02-28
  • 1970-01-01
  • 2021-10-21
  • 2016-04-21
  • 2021-06-02
相关资源
最近更新 更多