• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

296
Views
El código JavaScript no se ejecuta en el orden deseado (Node.js, MongoDB)

Sé acerca de la E/S sin bloqueo de Node.js y cuáles son las funciones asíncronas, pero tengo problemas para señalar por qué este código se ejecuta como se ejecuta.

Me estoy conectando a una colección MongoDB, buscando duplicados, colocando los primeros valores que se repiten en un objeto de matriz (dupIndex). Veo 2 valores cuando la matriz se imprime ( console.log(dupIndex); ), pero 0 cuando uso la propiedad .length más tarde ( console.log(dupIndex.length); ), cuando en realidad espero 2.

Me gustaría continuar y manipular la colección con los datos que tengo en dupIndex (como usar el método deleteMany), pero si muestra 0, no puedo, al menos no así. ¿Alguien puede explicar esto y ayudarme con esto?

¡Gracias!

 //connect us to a running MongoDB server const {MongoClient, ObjectID} = require('mongodb'); var dataBase = "TodoApp"; //connecting to a database //connects to the database /TodoApp, if no such db exists it auto creates it MongoClient.connect(`mongodb://localhost:27017/${dataBase}`, (err, db)=>{ if(err){ //return or 'else' - so if an error happens, it won't continue return console.log(`Unable to connect. Error: ${err}`); } console.log(`Connected to MongoDB server. Database: ${dataBase}.`); var dupIndex = []; //find all db.collection('Todos') .find() .toArray().then((docs) => { for ( var i =0; i< docs.length -1; i++){ for(var j =i+1; j< docs.length; j++){ if(docs[i].text === docs[j].text) { console.log(`in`); dupIndex.push(docs[i].text); i++; } } } console.log(dupIndex); }, (err)=> { console.log(`unable to fetch`); }); console.log(dupIndex.length); // for(var i = 0; dupIndex) //close the connection to the db db.close(); });
about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

Porque console.log(dupIndex.length); se ejecuta antes de sus bucles anidados.

 db.collection('Todos') .find() .toArray()

Esta es una llamada asíncrona y el control se pasa a console.log(dupIndex.length); intenta escribir console.log(dupIndex.length); al lado de console.log(dupIndex);

Por ejemplo:

 db.collection('Todos') .find() .toArray().then((docs) => { for ( var i =0; i< docs.length -1; i++){ for(var j =i+1; j< docs.length; j++){ if(docs[i].text === docs[j].text) { dupIndex.push(docs[i].text); i++; } } } return dupIndex; }, (dupIndexRecieved)=> { console.log(dupIndexRecieved.length); data recieved here }, (err)=> { console.log(`unable to fetch`); });
about 3 years ago · Santiago Trujillo Report

0

//conectarnos a un servidor MongoDB en ejecución

 const {MongoClient, ObjectID} = require('mongodb'); var dataBase = "TodoApp"; //connecting to a database //connects to the database /TodoApp, if no such db exists it auto creates it MongoClient.connect(`mongodb://localhost:27017/${dataBase}`, (err, db)=>{ if(err){ //return or 'else' - so if an error happens, it won't continue return console.log(`Unable to connect. Error: ${err}`); } console.log(`Connected to MongoDB server. Database: ${dataBase}.`); var dupIndex = []; //find all db.collection('Todos') .find() .toArray().then((docs) => { for ( var i =0; i< docs.length -1; i++){ for(var j =i+1; j< docs.length; j++){ if(docs[i].text === docs[j].text) { console.log(`in`); dupIndex.push(docs[i].text); i++; } } } //Mongo db find returns a promise. The value you are accessing with the then function. So whatever you want to do with the db query return value you have to do it here inside the then function. console.log(dupIndex.length); console.log(dupIndex); // for(var i = 0; dupIndex) //close the connection to the db db.close(); }, (err)=> { console.log(`unable to fetch`); }); //when you make the call here its get called before the then function. Thats why the length is zero. });
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error