对于那些使用 MongoDB 驱动程序 4.x 的人,我找到了findOneAndUpdate 的解决方法:
const toInsert = {
_id: mongo.ObjectId(),
someField: 'hello',
someOtherField: 'world'
};
const options = { upsert: true, returnDocument: 'after' };
const { value: document } = await db.collection.findOneAndUpdate(
toInsert,
{ $set: {} },
options
);
注意toInsert 中的_id 是新生成的ObjectId。
更新是空的 ({ $set: {} }) 并且什么都不做,因为我们不需要更新,我们只想更新我们的文档。仍然需要它,因为更新不能是 null 或空对象。
由于returnDocument 选项,新创建的文档将作为结果中的值返回。
为了避免空更新,另一种解决方案是使用$setOnInsert:
const toInsert = { someField: 'hello', someOtherField: 'world' };
const options = { upsert: true, returnDocument: 'after' };
const { value: document } = await db.collection.findOneAndUpdate(
{ _id: mongo.ObjectId() },
{ $setOnInsert: toInsert },
options
);