有一段代码用node.js
查询来自mongodb的数据:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
//a query that returns all the documents
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
var result = findDocuments(db, function() {
db.close();
});
});
//export the query result,but it doesn't work because it is a local variable in `MongoClient.connect()`
export {result}
问题:
我想导出变量result
,但它不起作用,因为它是MongoClient.connect()
中的局部变量。我该怎么办?
答案 0 :(得分:0)
在函数之外定义它,如
var result
答案 1 :(得分:0)
您需要在文档中全局定义它。
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var result; //define it out here to be able to use it on anywhere
//a query that returns all the documents
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
result = findDocuments(db, function() { //give it its value
db.close();
});
});
//export the query result,but it doesn't work because it is a local variable in `MongoClient.connect()`
export {result}
答案 2 :(得分:0)
如果您使用的是ES6
,我建议您使用关键字let/const
代替var
。
现在关于你的问题为什么要以这种方式导出结果?
您应该创建一个函数connect()
并将其导出。然后在你的控制器中,调用这个函数并处理结果。
这里的连接是完全异步和不受控制的,这是非常糟糕的行为。
做什么的例子:
档案mongodb.es6
export default class Mongodb {
connect() {
...
}
...
}
档案main.es6
const mongodbObject = new Mongodb();
mongodbObject.connect()
.then(() => {
// I am connected so I can do whatever I want
})
.catch((err) => {
// I have an error and do something about it
});
答案 3 :(得分:0)
不要这样做!
执行文件时,仅查询数据。我没有理由这样做。
而是从此文件中公开一个函数,该函数将连接到数据库,查询并返回结果对象,每次调用它。
export {
getResult: function(query, callback) {
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
if (err) return callback(err);
console.log("Connected correctly to server");
result = findDocuments(db, function() {
db.close();
});
callback(null, result);
});
}
}