猫鼬插件不挂钩 findOneAndUpdate

时间:2021-04-11 21:05:24

标签: javascript node.js mongodb mongoose plugins

我像这样设置了一个猫鼬模式:

const expertSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  contactMethods: {
    type: [ContactMethod.schema],
  }
})

expertSchema.plugin(autoIncrement.plugin, {
  model: 'EXP-',
  startAt: 1,
  prefix: 'EXP-'
});

const Expert = mongoose.model('Expert', expertSchema);

const contactMethodsSchema = new mongoose.Schema({
  type: {
    type: String,
    required: true,
  },
  value: {
    type: String,
    required: true,
  },
  preferred: {
    type: Boolean
  }
});

contactMethodsSchema.plugin(autoIncrement.plugin, {
  model: 'CON-',
  startAt: 1,
  prefix: 'CON-'
});
const ContactMethod = mongoose.model('ContactMethod', contactMethodsSchema)

我正在使用 mongoose-auto-increment 插件自动增加我的 monogodb 文档的 id(实际上使用 this fork,但它们基本相同)

我有一些代码可以为我的开发提供种子。重启时的 db 如下所示:

const contMethod1 = new models.ContactMethod({
  type: 'email',
  value: "janedoe@acme.org",
  preferred: false,
});

const contMethod2 = new models.ContactMethod({
  type: 'phone',
  value: "+12125550711",
  preferred: true,
});

const expert1 = new models.Expert({
  firstName: 'Jane',
  lastName: 'Doe',
  contactMethods: [contMethod1, contMethod2]
});

expert1.save();

这段代码效果很好,我最终得到了一个看起来像这样的文档:

{
  "_id": "EXP-1",
  "firstName": "Jane",
  "lastName": "Doe",
  "contactMethods": [{
      "type": "email",
      "value": "janedoe@acme.org",
      "preferred": false,
      "_id": "CON-1"
    },
    {
      "type": "phone",
      "value": "+12125550711",
      "preferred": true,
      "_id": "CON-2"
    }
  ]
}

但是,当我的前端将此编辑后的数据发回给我时,我得到的 json 如下所示:

{
  _id: "EXP-1",
  "contactMethods": [{
      "type": "email",
      "value": "janedoe@acme.org",
      "preferred": false,
      "_id": "CON-1"
    },
    {
      "type": "phone",
      "value": "+12125550711",
      "preferred": true,
      "_id": "CON-2"
    },
    {
      "type": "whatsapp",
      "value": "+123456789",
      "preferred": false
    }
  ]
}

现在我想要的是更新现有的嵌入文档和/或根据需要添加新文档。我为此目的设置了这段代码(我很欣赏可能有更智能的方法来实现这一点,但即便如此,它还是“有效”):

req.body.contactMethods.map((_, index) => {
  if (_._id) {
    expert = req.context.models.Expert.findOneAndUpdate({
      "contactMethods._id": _._id
    }, {
      $set: {
        "contactMethods.$.type": _.type,
        "contactMethods.$.value": _.value,
        "contactMethods.$.preferred": _.preferred
      }
    }, {
      useFindAndModify: false,
      returnOriginal: false,
      runValidators: true
    })
  } else {
    expert = req.context.models.Expert.findOneAndUpdate({
      "_id": req.user._id,
    }, {
      $push: {
        "contactMethods": _
      }
    }, {
      useFindAndModify: false,
      returnOriginal: false,
      runValidators: true
    })
  }
})

不幸的是,在这种情况下,我的插件不会“触发”或调用,我最终在集合中更新了一个文档,该文档缺少新推送的 contactMethod 的“_id”属性。

为什么我的插件没有在 findOneAndUpdate 调用中被调用?

我找到了 this question 但我的插件不使用 ES6 语法。我还发现了 this comment,但当前的猫鼬文档不再说明这一点,所以我有点希望他们可能会更改/修复它。

谢谢! (第一个问题,呸..)

1 个答案:

答案 0 :(得分:0)

我最终通过更改代码并将添加的新联系方法拆分为两个操作来解决(或者更确切地说是解决此问题):findOne 和 save,如下所示:

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Factories\Sequence;

class TestSeeder extends Seeder
{
    public function run()
    {
        \App\Models\Test::factory(1000)
           ->state(new Sequence(
             fn () => ['timestamp' => now()->addMinutes(5)->toDateTimeString()],
           ))
           ->create();
    }
}