嵌套数组中的猫鼬唯一文档

时间:2021-04-03 16:56:57

标签: node.js mongodb mongoose

我有以下架构,并且需要 method 在一个文档的 methods 数组中是唯一的:

const gatewayIntegration = new Schema(
  {
    gateway: { type: Schema.Types.ObjectId, ref: 'Gateway', required: true },
    methods: [
      {
        method: {
          type: Schema.Types.ObjectId,
          ref: 'Method',
          unique: true,
        },
        commId: { type: Number, unique: true },
        active: Boolean,
      },
    ],
})

{
        "_id" : 1,
        "gateway" : 1,
        "methods" : [
                {
                        "_id" : 1,
                        "method" : 1, 
                        "commId" : 100,
                        "activo" : false
                },
                {
                        "_id" : 2,
                        "method" : 1, // should not be allowed
                        "commId" : 100,
                        "activo" : false
                }
        ]
}

实际上,如果在数组中找不到该方法,我将使用 push() 更新网关方法,但需要知道如何设置拒绝重复方法的约束。

// Check if method exists (is it possible to do this with mongoose??)
const method = doc.methods.find((x) => x.method._id == req.body.idMethod);
if (!method)
    // when push a new method the unique constraint is not working and a duplicated method is added.
    doc.methods.push({
        metodo: req.body.idMethod,
        commId: req.body.commId,
        active: req.body.active,
    });
else // update method.*

await doc.save();

谢谢

0 个答案:

没有答案