簡體   English   中英

使用mongo nodejs require('file.js') module.exports時如何處理結果

[英]how to process the result when using mongo nodejs require('file.js') module.exports

我正在用 nodejs + express + mongodb + ejs 構建一個應用程序。

對於這個問題:我有 2 個文件 (server.js + db.js) 所有與 mongo 相關的東西我都放在那個單獨的文件 (db.js) 中,以便我可以在那里進行所有數據庫查詢。 問題:結果返回一個查詢對象,我不知道如何在迭代中使用它(列出結果文檔),我將其發送給 ejs。 當我做 console.log(result.length) 時顯示“未定義”。

有什么想法嗎?

/* server.js: */

let db = require("./db.js");
app1.get("/page", function (req, res) {
    let result= db.getPLayers(); // console.log(result); ==> query object, see below => Q
    let qty = result.length; // console.log(qty); ==> undefined
    res.render('adm', { playersFound: result}); // sent to render result via ejs
}

/* db.js */

module.exports.getPLayers = function() {
    return Player.find({});
}

// => Q 這是我作為結果得到的查詢對象:

> Query {   _mongooseOptions: {},   _transforms: [],   _hooks: Kareem {
> _pres: Map {}, _posts: Map {} },   _executionCount: 0,   mongooseCollection: 
NativeCollection {
>     collection: Collection { s: [Object] },
>     Promise: [Function: Promise],
>     _closed: false,
>     opts: { .... and lots more
>
// server.js
app1.get("/adm", function (req, res) {
let db = require("./db.js");
let playersList;
let teamsList;    
db.getPLayers().then(function () {        
    playersList = this.docs;
})
    .then(function () {
        db.getTeams().then(function () {                
            teamsList = this.docs;
        })
            .then(function () {                    
                res.render('adm', { playersFound: 
playersList, teamsFound: teamsList });//, teamsFound: dbteamsFound });
            });
    });
});
// db.js
exports.getPLayers = function(){
return Player.find({}, function (err, docs) {    
    this.docs=docs; console.log("==> db exporting getPlayers :"+ 
this.docs.length);  
});
}
exports.getTeams = function(){
return Team.find({}, function (err, docs) {    
     this.docs=docs; console.log("==> db exporting getTeams :"+ 
 this.docs.length);  
 });
 }

暫無
暫無

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

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