mongodb - mongoose同時查詢,如何用promise.all包裝
滿天的星座
滿天的星座 2017-05-02 09:23:25
0
1
513

想實現的是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
                })
             })
})
滿天的星座
滿天的星座

全部回覆(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
    })
})

大概写了下,你试试呢

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!