Node.js 嵌套数组中的Mongoose唯一文档

Node.js 嵌套数组中的Mongoose唯一文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有以下架构,需要方法在方法数组中对一个文档唯一: const gatewayIntegration = new Schema( { gateway: { type: Schema.Types.ObjectId, ref: 'Gateway', required: true }, methods: [ { method: { type: Schema.Types.ObjectId, ref: 'Method'

我有以下架构,需要方法方法数组中对一个文档唯一:

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,
      },
    ],
})

实际上,我正在使用
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();

谢谢

// 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();