节点不打印值且未完成

时间:2019-12-10 16:50:54

标签: node.js mongodb

我正在尝试从MondoDB检索数据并将结果打印到控制台。 数据不可视化,脚本不返回。 问题出在哪里? 谢谢。

import * as mongoProxy from "mongodb";
import { exists } from "fs";


namespace code {

interface ICountry{
    TestIField1: string;
    TestIField266A3: string;     
}

interface IProjection{
    projection: {"TestIField1": number, "TestIField2": number}
};

interface IFilter {
    filter: {
     "this_is_valid": {$ne: boolean}
    }
};


class CreateMembers {

private mongo_username = "mongo_credentials";
private mongo_password = "mongo_credentials";
private mongo_db = "DB_NAME";
private mongo_host ="mongo_host:27017";
private mongo_replica_set = "mongodev";

private  mongo_url = `mongodb://${this.mongo_username}:${this.mongo_password}@${this.mongo_host}/${this.mongo_db}?replicaSet=${this.mongo_replica_set}`;
private  env = "development";

private async getDataFromDb(collectionName: string, filter: IFilter, projection:IProjection) {

console.log("Connecting...");
const dbConn = await mongoProxy.connect(this.mongo_url);
const db = dbConn.db(this.mongo_db);
if (dbConn.isConnected()) {
    console.log("Connected!");
const mongoResult=db.collection(collectionName).find<ICountry>(
    {"this_is_valid":{ $ne: true }},
    {projection: {"TestIField1": 1, "TestIField2": 1}}
    );


    mongoResult.map((r)=>{
        console.log(`DEBUG-->: ${r}`);
    });

console.log("Data retrieved... returning to run.");



return mongoResult;
    }
    else{console.log("CONNECTON FAILED!");

    }

}

public async run(){

    console.log("RUN1");
const projection : IProjection = {projection: {"TestIField1": 1, "TestIField2": 1}};
const filter : IFilter = {filter: {"this_is_valid": {$ne: true}}};

const collectionName="country";



    // const filter={"this_is_valid":{ $ne: true }};
    // const projection={projection: {"TestIField1": 1, "TestIField2": 1}};
    let countryRecords=await this.getDataFromDb(collectionName, filter, projection);
    console.log("RUN2");
    if (countryRecords){
        countryRecords.forEach((r)=>{
        console.log(`DEBUG-->: ${r}`);
    });
}
console.log("RUN3");

}

}

let myClass=new CreateMembers();
myClass.run();

}

控制台上的输出:
RUN1
正在连接...
已连接!
检索到的数据正在返回运行。
RUN2
RUN3

//此处脚本仍在运行;没有返回控制台。

1 个答案:

答案 0 :(得分:1)

.find返回承诺,所以您应该等待它:

        const mongoResult = await db.collection(collectionName).find<ICountry>(
          { "this_is_valid": { $ne: true } },
          { projection: { "TestIField1": 1, "TestIField2": 1 } }
        ).toArray();

该脚本仍在运行,因为您需要使用以下命令关闭mongo连接:

dbConn.close()