mongodb - mongoose同时查询,如何用promise.all包装

查看:159
本文介绍了mongodb - mongoose同时查询,如何用promise.all包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

想实现的是 reply - save后,同时操作 topic表和user表,然后一起返回,不知怎么用promise.all来包装这2个 查询更新 操作,希望大家能帮我解决下= =

更新:下面是修改好的.

/* 回复 话题 */
router.post('/reply', (req, res, next) => {
  let topic_id = req.body.topic_id,
      content  = req.body.content

  let replyEntity = new replyModel({
    author: req._id,
    topic: topic_id,
    content
  })

  replyEntity.save()
             .then((_new_reply) => {
                Promise.all([
                  topicModel.findByIdAndUpdate(topic_id, {
                    $inc: {replyNum: 1},
                    last_reply_author: req._id,
                    last_reply_time: Date.now()
                  }),
                  userModel.findByIdAndUpdate(req._id, {
                    $push: {replies: _new_reply._id}
                  })
                ])
                .then((res_arr) => {
                  return res.json({
                    status: 0
                  })
                })
                .catch((err) => {
                  return res.json({
                    status: -1
                  })
                })
             })
             .catch((err) => {
                return res.json({
                  status: -1
                })
             })
})

解决方案

replyEntity.save()
    .then((_new_reply) => {

        var topic = function (topic_id,authorId) {
            return topicModel.findByIdAndUpdate(topic_id, {
                $inc: {replyNum: 1},
                last_reply_author: authorId,
                last_reply_time: Date.now()
            }).exec();
        }
        var user = function (authorId,replyId) {
            return userModel.findByIdAndUpdate(authorId, {
                $push: {replies: replyId}
            }).exec();
        }
        return Promise.all([topic(topic_id,req._id), user(req._id,_new_reply._id)])
            .then(function (results) {
                console.log('===results===',results);
                return res.json({
                    status: 0
                })
        }).catch((err) => {
                return res.json({
                    status: -1
                });

    }).catch((err) => {
    return res.json({
        status: -1
    })
})

大概写了下,你试试呢

这篇关于mongodb - mongoose同时查询,如何用promise.all包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆