JavaScript代码无法以所需顺序运行(Node.js,MongoDB)

时间:2017-01-15 13:12:58

标签: javascript arrays node.js mongodb algorithm

我知道Node.js的非阻塞I / O以及什么是异步函数,但是我很难指出为什么这个代码会像运行一样运行。

我正在连接MongoDB集合,搜索重复项,将重复的第一个值放在数组对象中(dupIndex)。 我在阵列打印时看到2个值( console.log(dupIndex); ),但是当我稍后使用.length属性时会看到0( console.log(dupIndex.length); ) - 当我真正期待2。

我想继续使用dupIndex中的数据(比如使用deleteMany方法)来操作集合,如果它显示0,我不能,至少不喜欢这样。有人能解释一下并帮助我吗?

谢谢!

//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 t o fetch`);
    });

    console.log(dupIndex.length);
    // for(var i = 0; dupIndex)
    //close the connection to the db
    db.close();
});

2 个答案:

答案 0 :(得分:2)

因为console.log(dupIndex.length);在嵌套循环之前运行。

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

这是一个异步调用,控件传递给console.log(dupIndex.length); 尝试编写console.log(dupIndex.length);在console.log旁边(dupIndex);

例如:

 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 t o fetch`);
});

答案 1 :(得分:0)

//将我们连接到正在运行的MongoDB服务器

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 t o fetch`);
});

//when you make the call here its get called before the then function. Thats why the length is zero. 

});