0

My code :

const mongoose = require("mongoose");



async function run() {
    await mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true, useUnifiedTopology: true });

    const citySchema = new mongoose.Schema({
        name: String,
        country: String
    });
    const City = mongoose.model('serverdatas', citySchema);


    const docs = await City.find({name: "Paris"});


    return docs;

}

var test;

test = run();

console.log(test);

Output :

Promise { <pending> }

So, what i'm trying to do is to assign test with docs. I want to assign it to a global variable, not only console.log it. The problem is that when I execute my code, I get a Promise. I am not a good developper, so I don't know how to get the data out of the Promise, and assign it to test.

1 Answers1

1

You are just calling a promise function. To resolve it use then() and catch()

i.e

var test;
run().then(res => test = res);

Update to your comment: That's because console.log() happens before run() promise finishes.

try this:

const mongoose = require("mongoose");



async function run() {
    await mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true, useUnifiedTopology: true });

    const citySchema = new mongoose.Schema({
        name: String,
        country: String
    });
    const City = mongoose.model('serverdatas', citySchema);


    const docs = await City.find({name: "Paris"});


    return docs;

}

var test;
run().then(res => {
  test = res;
  console.log(test);
});

The console.log just doesn't wait for the promise to finish so you get undefined before the variable test is populated by the promise.. even though eventually test will be populated. You need to make sure you script is aware of promises.

fedesc
  • 2,554
  • 2
  • 23
  • 39