【发布时间】:2017-05-30 09:50:49
【问题描述】:
我知道 Node.js 的非阻塞 I/O 以及什么是异步函数,但我很难指出为什么这段代码运行起来像它运行一样。
我正在连接到 MongoDB 集合,搜索重复项,将第一个重复的值放入数组对象 (dupIndex) 中。 当数组打印时我看到 2 个值 (console.log(dupIndex);),但是当我稍后使用 .length 属性时看到 0 (console.log(dupIndex.length); em>) -- 当我真正期待 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();
});
【问题讨论】:
标签: javascript arrays node.js mongodb algorithm