gpt4 book ai didi

node.js - mongoDB同时更新2个集合

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:14 26 4
gpt4 key购买 nike

我正在寻找同时更新 2 个集合的不同方法,在以下情况下我更新了医生的病例数

我的 Mongo DB 文档结构:

医生收藏:

 { 
"_id" : ObjectId("5a18a637346826574416a588"),
"doc_fname" : "Bob",
"doc_lname" : "Smith",
"numOfCases" : NumberInt(6),
"__v" : NumberInt(0)
}

客户案例集合:

{ 
"_id" : ObjectId("5a18c02221344b58585105ea"),
"doctor_id" : ObjectId("5a18a637346826574416a588"),
"cust_fname" : "test",
"cust_lname" : "test",
"case_type" : "Crowns",
"__v" : NumberInt(0)
}

NodeJS Mongoose 代码:

var NewCustomerCase = req.body;


CustomerCases.create(NewCustomerCase, function(err,CustomerCase){
if(err){
throw err;
}
else{
var query = {_id:NewCustomerCase.doctor_id};
// if the field doesnt exsit $set will set q new field
var update = {
'$inc': {'numOfCases': 1}
}
// when true return the updated document
var options = {new:true};
Doctors.findOneAndUpdate(query,update,options,function(err,updatedDocter){
if(err){
throw err;
}
});
res.json(CustomerCase);
}

});

这种方法效果很好,有没有更好的方法来解决这个问题,据我所知不可能同时执行2个集合

最佳答案

如果您要更新的文档彼此不依赖,您可以同时更新它们。例如,做出两个 promise ,然后使用 Promise.all() 同时运行它们:

const customerPromise = CustomerCases.create(NewCustomerCase);
const doctorPromise = Doctors.findOneAndUpdate(query, update, options);

Promise.all([customerPromise, doctorPromise])
.then((result) => {
return res.status(200).json(result);
}).catch((err) => {
return res.status(400).json(err);
});

当客户和医生 promise 都得到解决时,Promise.all() 返回的 promise 将得到解决。文档是here .

如果出现错误就会出现问题。如果客户未能更新,医生仍会将 numOfCases 加 1。如果医生文档未能更新,仍将生成客户案例。所以事实上,文档之间确实存在一些依赖关系,而 Promise.all() 可能毕竟不是一个好的解决方案。这通常是事务发挥作用的地方,但 MongoDB 中的事务超出了本答案的范围,所以我将发布此 link相反。

您已经通过回调按顺序运行数据库操作。这是基于 async/await 的更现代的方法。 :

try {
const newCustomerCaseFromDb = await CustomerCases.create(NewCustomerCase);
const doctorUpdated = await Doctors.findOneAndUpdate(query, update, options);
return res.status(200).json({ newCustomerCaseFromDb, doctorUpdated });
} catch(err) {
return res.status(400).json(err);
}

使用 await 的函数需要 async关键字。

首先创建客户案例。如果失败,它会跳到 catch block 中。如果成功,它将继续寻找并更新医生。使用 await 使其看起来像同步代码。

关于node.js - mongoDB同时更新2个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47481757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com