如何使用Node.js/Mongoose/MongoDB同时更新2个集合?



感谢您花时间阅读本文。

我正在用Node.js/Mongoose/MongoDB制作博客应用程序。目前,我正在努力弄清楚如何在同一时间更新2个集合。我的userSchema有postSchema数组,我希望在更新文档时同时更新用户和帖子集合。

我的代码在这里:

const postSchema = new mongoose.Schema({
title: String,
content: String,
author: String
});
const Post = mongoose.model('Post', postSchema);
const userSchema = new mongoose.Schema({
username: String,
password: String,
displayName: String,
provider: String,
posts: [postSchema],
drafts: [postSchema]
});
const User = mongoose.model('User', userSchema);

app.post('/edit/:title', function (req, res) {
Post.findOneAndUpdate({ title: req.params.title }, {
title: req.body.title,
content: req.body.content
}, function (error, post) {
if (error) {
console.log(error);
} else {
res.redirect('/dashboard');
}
});
});

目前,我的代码只更新posts集合,并且用户集合内的postSchema数组保持不变。有人能帮我解决这个问题吗?

有两种方法

选项1

区间(),.catch()块

Post.findOneAndUpdate({
Do your stuff here
}).then((result)=>{
Do your stuff here with result from step above
}).catch((err)=>{
Handle Error
});

选项2

使用async/await

async function (req, res) {
const postResult = await Post.findOneAndUpdate({ title: req.params.title }, {
title: req.body.title,
content: req.body.content
});
const userResult = await User.findOneAndUpdate({Do some stuff here});

if(!postResult || !userResult){
return new Error(...)
}
return 

由于没有太多的代码共享,所以不能按原样使用。但是这些选项背后的逻辑即使在你的代码中也是一样的。

最新更新