D
D
depressionofoleg2021-04-14 10:11:43
MongoDB
depressionofoleg, 2021-04-14 10:11:43

How to get data from mongoDB from collection to external variable?

Good afternoon. Started to comprehend databases in nodejs. Got a question. How to write data to an external variable, so that later it can be processed and sent to the front.

const MongoClient = require("mongodb").MongoClient;


let variableArr = [];
const mongoClient = new MongoClient(url, { useUnifiedTopology: true });
 
mongoClient.connect(function(err, client){
      
    const db = client.db("variabledb");
    const collection = db.collection("variables");
 
    if(err) return console.log(err);
      
    collection.find().toArray(function(err, results){
        
        results.forEach(item => variableArr.push(item))
        client.close();
    });

console.log(variableArr); // Выдает также пустой массив


I understand that the problem lies in asynchrony, but I just can’t figure out how to fix this problem.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bodrych, 2021-04-14
@depressionofoleg

https://docs.mongodb.com/drivers/node/usage-exampl...

const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
  "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
  try {
    await client.connect();
    const database = client.db("sample_mflix");
    const movies = database.collection("movies");
    // Query for a movie that has the title 'The Room'
    const query = { title: "The Room" };
    const options = {
      // sort matched documents in descending order by rating
      sort: { rating: -1 },
      // Include only the `title` and `imdb` fields in the returned document
      projection: { _id: 0, title: 1, imdb: 1 },
    };
    const movie = await movies.findOne(query, options);
    // since this method returns the matched document, not a cursor, print it directly
    console.log(movie);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question