node.js mongodb javascript范围界定混乱 [英] node.js mongodb javascript scoping confusion
问题描述
我正在开发一个没有mongoose的express.js应用程序。
I'm developing a express.js application, without mongoose.
我想要做的是将函数封装到函数中的mongodb中,传递函数一些参数,并从mongodb获取数据。
What I'm trying to do is, to encapsulate calls to mongodb inside a function, pass the function some parameter and get the data back from mongodb.
我遇到的问题由以下代码解释:
The problem I'm running into is explained by the code below
function get_data()
{
var mongo = require('mongodb'),Server = mongo.Server,Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('test', server);
db.collection('test_collection', function(err, collection) {
collection.find().toArray(function(err, items) {
var data = items;
});
});
console.log(data);
console.log("in get");
return data;
}
如何返回我从这个函数从mongo db中提取的项目Array。
How do I return the items Array I pulled from mongo db from this function.
我想知道JavaScript中的范围工作原理,如何将项目放在变量中并从get_data函数返回。
I want to know how scoping works in javascript and how do I put the items in a variable and return them from the get_data function.
答案
我修复了代码。它现在可以工作,看起来像这样。
I fixed the code. It now works and looks like this.
function get_data(callback) {
var mongo = require('mongodb'),Server = mongo.Server,Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('test', server);
db.open(function(err, db) {
if (err) return callback(err);
db.collection('test_collection', function(err, collection) {
if (err) return callback(err);
collection.find().toArray(callback);
});
});
}
get_data(function(err, items) {
// handle error
console.log(items);
});
推荐答案
由于项目是从MongoDB异步检索的, get_data
需要接受将用于返回结果的回调。我相信你还需要明确的打开
数据库连接。
Since the items are retrieved from MongoDB asynchronously, the function get_data
needs to accept a callback that will be used to return the results. I believe you'll also need to explicitly open
the database connection.
function get_data(callback) {
...
db.open(function(err, db) {
if (err) return callback(err);
db.collection('test_collection', function(err, collection) {
if (err) return callback(err);
collection.find().toArray(callback);
});
});
}
get_data(function(err, items) {
// handle error
console.log(items);
});
这篇关于node.js mongodb javascript范围界定混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!