saulable
saulable

Reputation: 485

Wait until mongoose has saved to DB before calling the next await function?

So I have a call to a function which creates a DB collection to mongoose, then right after it I set some variables which are calls to the same collection. However, the promise is returning before the actual save is made to MongoDB and I'm getting the error on the variables :

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'likes' of null

How do I make sure that the save is complete to the DB before the calls to the variables?

Code below:

var dbcreate_stats = await dailyStats.createCollection();

async createCollection(){
        var checkUnique = await dailyStats.findOne({formatted_date: newdate}, function(err,docs){
        });
        if (checkUnique == null) {
            var dailyInfo = new dailyStats({
                likes: 0,
                follows: 0,
                comments: 0,
                unfollows: 0,
                profiles_visited: 0,
                new_profiles_found: 0,
                formatted_date : newdate,
                utc_date: new Date(),
            });
            // await dailyInfo.save(function(err, objs, numAffected){
            //  if (err) throw err;
            //  console.log(numAffected);
            // });
            dailyStats.create(dailyInfo, function(err,obj, numAffected){
                console.log('inserted');
            });
        }
    }

dailyLikes = await dailyStats.dailyLikesCount();
dailyFollows = await dailyStats.dailyFollowsCount();
dailyComments = await dailyStats.dailyCommentsCount();

async daily(){
    var foo = await dailyStats.findOne({formatted_date: newdate});
    return foo;
}
async dailyLikesCount(){
    let daily = await this.daily();
    return daily.likes;
}
async dailyFollowsCount(){
    let daily = await this.daily();
    return daily.follows;
}
async dailyCommentsCount(){
    let daily = await this.daily();
    return daily.comments;
}

Upvotes: 1

Views: 1804

Answers (2)

shubham verma
shubham verma

Reputation: 53

dailyStats.findOne should not handle callback it should be returnpromise.

dailyStats.findOne(query).exec();

And in your create function inside if block it should also return with Promise.

var dbcreate_stats = await dailyStats.createCollection();
async createCollection(){
    var checkUnique = await dailyStats.findOne({formatted_date: newdate}).exec();// This will return Promise.
    if (checkUnique == null) { 
        var dailyInfo = new dailyStats({
            likes: 0,
            follows: 0,
            comments: 0,
            unfollows: 0,
            profiles_visited: 0,
            new_profiles_found: 0,
            formatted_date : newdate,
            utc_date: new Date(),
        });
    return  dailyStats.create(dailyInfo);// This will return Promise.
    }
}

Upvotes: 0

Artur P.
Artur P.

Reputation: 896

async await work only if function returns Promise.

var checkUnique = await dailyStats.findOne({formatted_date: newdate}).exec(); //returns promise


var foo = await dailyStats.findOne({formatted_date: newdate}).exec();

This should work

Upvotes: 1

Related Questions