Saeed Heidarizarei
Saeed Heidarizarei

Reputation: 8916

mongoose Chaining with then and catch

How To Convert This Function to Chaining with then and catch?
Is better to Chained?
I mean User.findOne().then().catch()

User.findOne({_id: msg.chat.id}, (err, doc) => {
    if (err) {
      console.log(err);
    }

    if (doc) {
      console.log(doc.name);
    } else {
      console.log('Empty');
    }
  });

Upvotes: 0

Views: 1428

Answers (2)

Fernando Carvajal
Fernando Carvajal

Reputation: 1945

Better switch to ES2017 async/await syntax, you can avoid Promise Hell

async function foo () {
    try {
        var doc = await User.findOne({_id: msg.chat.id}).exec()         
        if (doc)
            return console.log(doc.name);
        console.log('Empty');    
    } catch (err) { console.log(err) }
}

foo()

This will help you when you're going to nest DB calls or using for...loops.

async function foo () {
    try {
        var users = await User.find({}).exec()

        for (var user in users) {
            var tweets = await Tweet.find({_user: user._id}).exec()
            user.tweets = tweets.map(t => t.text)
            await user.save() 
        }

    } catch (err) { console.log(err) }
}

foo()

Upvotes: 1

Alex Young
Alex Young

Reputation: 4039

The function you pass to then is called with the returned document (or null) if the operation succeeds, and the catch is called with the error if the operation fails (e.g. no connection). Putting it together looks like this:

User.findOne({_id: msg.chat.id})
    .then(doc => {
        if (doc) {
            console.log(doc.name);
        } else {
            console.log('Empty');
        }
    }).catch(err => {
        if (err) {
            console.log(err);
        } 
    });

As an aside, when you are searching for one document by id, then you can use findById:

User.findById(msg.chat.id)
    .then(doc => {
        if (doc) {
            console.log(doc.name);
        } else {
            console.log('Empty');
        }
    }).catch(err => {
        if (err) {
            console.log(err);
        } 
    });

Upvotes: 4

Related Questions