我必须更新两个集合。我希望确保这两个集合要么更新,要么不更新。
我创建了两个更新的简单示例(它们在这里都使用相同的集合,但它们可以是不同的):
await this.client.connect();
const session = this.client.startSession();
try{
const transactionOptions = {
readPreference: 'primary',
readConcern: { level: 'local' },
writeConcern: { w: 'majority' }
};
await session.withTransaction(async () => {
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, {$set: {"gender": "F10"} });
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, "d");
}, transactionOptions)
}
finally{
await session.endSession();
}现在,如果性别的初始值为空,""。然后在执行上面的代码后,最终的值应该仍然是"",因为第二次更新是无效的语法,并且会抛出异常。
但结果是gender:Male
发布于 2020-09-26 21:42:44
最终基于@D. SM的宝贵意见解决了这个问题。
await this.client.connect();
const session = this.client.startSession();
try{
const transactionOptions = {
readPreference: 'primary',
readConcern: { level: 'local' },
writeConcern: { w: 'majority' }
};
await session.withTransaction(async () => {
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, {$set: {"gender": "G2"} }, { session });
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, "G2", { session });
}, transactionOptions)
}
finally{
await session.endSession();
}即使在将会话传递给更新之后,事务似乎也无法工作。问题是我应该把它包装在{}中
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, {$set: {"gender": "G2"} }, { session });用代替
await this.client.db("Person").collection("persons").updateMany({ "phone": "23138213"}, {$set: {"gender": "G2"} }, session );https://stackoverflow.com/questions/64067167
复制相似问题