![](/img/trans.png)
[英]How can I retrieve document from mongodb base using mongoose on node.js?
[英]How can I update 2 collections at the same time using Node.js/Mongoose/MongoDB
感谢您花时间阅读本文。
我正在使用 Node.js/Mongoose/MongoDB 制作博客应用程序。 目前,我正在努力弄清楚如何同时更新 2 collections。 我的 userSchema 有 postSchema 的 arrays,我想在更新文档时更新用户和帖子 collections。
我的代码在这里:
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'); } }); });
目前,我的代码只更新帖子集合,用户集合中的 postSchema 的 arrays 保持不变。 谁能帮我解决这个问题?
你可以通过 2 种方式做到这一点
选项1
.then() &.catch() 块
Post.findOneAndUpdate({
Do your stuff here
}).then((result)=>{
Do your stuff here with result from step above
}).catch((err)=>{
Handle Error
});
选项 2
使用异步/等待
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
由于共享的代码不多,因此不能按原样使用..但即使在您的代码中,这些选项背后的逻辑也将保持不变..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.