Chaining mongoose promises

时间:2019-01-09 21:52:04

标签: mongoose promise

I need the second then() to run only after the first is completed. Here is my code sample:

Participant.findOne({ phone: phoneNumber })
              .then(participant => {
                if (
                  participant &&
                  participant.campaign.equals(campaign._id)
                ) {
                  participant.entries++;
                  participant.codes.push(sentCode);
                  participant.save();
                }
                if (participant === null) {
                  let newParticipant = {
                    phone: phoneNumber,
                    entries: 1,
                    codes: [sentCode],
                    campaign: campaign._id
                  };
                  new Participant(newParticipant)
                    .save()
                    .then()
                    .catch(err =>
                      console.log("Error creating new participants" + err)
                    );
                }
              })
              .then(participant => {
                ...
              }

Please will this work?

1 个答案:

答案 0 :(得分:0)

you must, use method Model.create() Participant.create()

Participant.findOne({
    phone: phoneNumber
}).then((participant) => {
    if(
        participant &&
        participant.campaign.equals(campaign._id)
    ) {
        participant.entries++;
        participant.codes.push(sentCode);
        return participant.save();
    }
    if(participant === null) {
        let newParticipant = {
            phone: phoneNumber,
            entries: 1,
            codes: [sentCode],
            campaign: campaign._id
        };
        return Participant.create(newParticipant);
    }
}, (errorCreate) => {
    console.log("Error creating new participants" + errorCreate)
}).then(participant => {
.....
}).catch(err => {
    //Global error
});