簡體   English   中英

節點不打印值並且不完成

[英]Node doesn't print values and does not finish

我正在嘗試從 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();

}

控制台輸出:
運行1
正在連接...
連接的!
數據檢索...返回運行。
運行2
運行3

//這里腳本還在運行; 沒有返回到控制台。

.find返回一個 promise,所以你應該等待它:

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

並且腳本仍在運行,因為您需要關閉 mongo 連接:

dbConn.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM