Mongoose: atomic FindOne-Or-Insert(), do not update existing instance if found
在猫鼬中,我寻求以原子方式执行
我无法找到一种使用
因此,我当前的非原子变通方法是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | const Foo = DB.model('foo', FooSchema) async function findOneAndUpdateFoo(jsonFoo, next) { const filter = { deletedAt: null } if (jsonFoo.dsAccountId) { filter.dsAccountId = jsonFoo.dsAccountId } if (jsonIntegration.dsUserId) { filter.dsUserId = jsonIntegration.dsUserId } if (jsonFoo.providerId) { filter.providerId = jsonFoo.providerId } const fooDoc = { name: jsonFoo.name, dsAccountId: jsonFoo.dsAccountId, dsUserId: jsonFoo.dsUserId, providerId: jsonFoo.providerId, providerName: jsonFoo.providerName, // Most of these fields could be empty accessToken: jsonFoo.accessToken, refreshToken: jsonFoo.refreshToken, scope: jsonFoo.scope, tokenType: jsonFoo.tokenType, expiresAt: jsonFoo.expiresAt } return await Foo.findOneAndUpdate( filter, // find a document with that filter fooDoc, // document to insert when nothing was found { upsert: true, new: true, runValidators: true } // options ) .catch(next) } |
建议?谢谢
您可以在更新参数中使用
1 2 3 4 5 | return await Foo.findOneAndUpdate( filter, // find a document with that filter {$setOnInsert: fooDoc}, // document to insert when nothing was found { upsert: true, new: true, runValidators: true } ) |
请注意,您还应该在