0

i have code blow and need to replace the "doc" (query result) with projectsDocument, but projectsDocument not defined in the function,please help me!!!!

var projectsDocument, categoryDocument; //empty
    projectsModel.find({}, {}, (err, doc) => {
        if (err) return next(err);
        if (doc) {
            projectsDocument = doc; 

        }
    });
    console.log(projectsDocument); //want to projectsDocument be equals to doc

[SOLVED]

i change my code to this and it works

    router.get('/', async(req, res, next) => {

    await projectsModel.find().then(function(doc) {
        projectsDocument = doc;
    }).catch(function(error) {
        console.log(error);
    });

});

1 Answers1

0

Because Javascript is async in nature means it does not execute instructions such as API calls synchronously (does not wait for the response).

Mongoose version > 4.0

projectsModel.find()
.then(function(doc){
   if (doc) {
        projectsDocument = doc; 
    }
})
.catch(function(err) {})

Mongoose version < 4.0

var projects = projectsModel.find().exec() //returns promise

projects.then(function(project){
    if (project) {
       projectsDocument = project;
    }
})
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25