【问题标题】:How can I update 2 collections at the same time using Node.js/Mongoose/MongoDB如何使用 Node.js/Mongoose/MongoDB 同时更新 2 个集合
【发布时间】:2021-05-11 00:47:07
【问题描述】:

感谢您抽出宝贵时间阅读本文。

我正在使用 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');
            }
        });
});

目前,我的代码只更新帖子集合,用户集合中的 postSchema 数组保持不变。谁能帮我解决这个问题?

【问题讨论】:

  • 您是否有意保留帖子数据的两份副本而不是对Post 的引用?
  • 您是指用户内部的“帖子”和“草稿”吗?我将它们用于不同的目的......请忽略那部分。我只想更新用户集合中的 postSchemas。
  • 有一个 Posts 集合,那么 Posts 也嵌入到 User 模式中。它似乎在重复数据

标签: javascript node.js mongodb mongoose


【解决方案1】:

你可以通过两种方式做到这一点

选项 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 

由于共享的代码不多,因此不能按原样使用。但即使在您的代码中,这些选项背后的逻辑也将保持不变..

【讨论】:

  • async/await 代码应该包含在 try/catch 中并在那里处理错误(例如 res.status(500))以模拟上面的 catch
猜你喜欢
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多