search

Home  >  Q&A  >  body text

mongodb - mongoose simultaneous query, how to wrap with promise.all

What I want to achieve is to operate the reply - save table and the topic table at the same time after user, and then return them together. I don’t know how to use promise.all to wrap these two query update operations. I hope you can help me solve it. = =

Update: The following is the modified version.

/* 回复 话题 */
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
                })
             })
})
滿天的星座滿天的星座2857 days ago656

reply all(1)I'll reply

  • 迷茫

    迷茫2017-05-02 09:25:25

    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
        })
    })

    I probably wrote it down, give it a try

    reply
    0
  • Cancelreply