[英]how to process the result when using mongo nodejs require('file.js') module.exports
I am building an application in nodejs + express + mongodb + ejs.我正在用 nodejs + express + mongodb + ejs 构建一个应用程序。
For this question: I have 2 files (server.js + db.js) All mongo related stuff I put in that separate file (db.js), so that I can do all database queries there.对于这个问题:我有 2 个文件 (server.js + db.js) 所有与 mongo 相关的东西我都放在那个单独的文件 (db.js) 中,以便我可以在那里进行所有数据库查询。 The problem: result returns a query object, and I dont know how I can use that in an iteration (to list the resulting docs), which I sent to ejs.
问题:结果返回一个查询对象,我不知道如何在迭代中使用它(列出结果文档),我将其发送给 ejs。 When I do console.log(result.length) is shows "undefined".
当我做 console.log(result.length) 时显示“未定义”。
Any thoughts?有什么想法吗?
/* server.js: */ /* 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 */ /* db.js */
module.exports.getPLayers = function() {
return Player.find({});
}
// => Q this is the query object that I get as result: // => 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.