我正在编写教程:http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/
我需要一些帮助来理解语法。下面是代码:
var mongo = require ('mongodb');
var Server = mongo.Server,
Db = mongo.db,
BSON = mongo.BSONPure;
var server = new Server ('localhost', 27017, {auto_reconnet:true});
db = new Db('winedb', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'winedb' database");
//Q1. Why are we passing "collection" ? Where did we declare "collection"?
db.collection('wines', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findById = function(req, res)
{
var id = req.params.id;
console.log('Retrieving wine: ' + id);
//Q2. Why do we need to pass function as a parameter? Where is "collection" declared?
db.collection('wines', function(err, collection)
{
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item)
{
res.send(item);
});
});
}
exports.findAll = function(req, res) {
db.collection('wines', function(err, collection) {
//Q3. Why do we not have to declare "items" anywhere?
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
三个问题:
Q1:为什么我们要传递“集合”?我们在哪里声明“集合”?
Q2:为什么我们需要将函数作为参数传递? “集合”在哪里声明?
问题3:为什么我们不必在任何地方声明“元素”?
最佳答案
问题1:为什么我们要传递“集合”?我们在哪里声明“集合”?
collection 是在此行创建的 db 对象的属性(实际上是方法):
db = new Db('winedb', server);
检查 mongodb api 以了解应如何使用它。
<小时/>问题2:为什么我们需要将函数作为参数传递? “收集”在哪里声明?
数据库查询非常慢。对于您的程序来说,在继续执行之前等待查询结果到来是没有意义的,因此查询是与其他代码并行进行的。您可能会遇到的问题是:如果此时执行 fork ,我如何获得查询的结果?答案是回调。
您需要将一个函数传递给集合方法,当结果准备好时它将调用该方法。结果作为参数传递给您的函数。收集方法的一个非常示意性的实现是:
function collection(name, callback) {
var result = // do stuff to get the result;
callback(result);
}
显然还有更多的内容,但这就是主要思想。
回顾一下:您需要传递一个函数作为参数才能接收结果。 db.collection 方法将使用查询结果填充函数中的集合参数(如果没有错误)。
<小时/>问题3:为什么我们不必在任何地方声明“元素”?
这个问题暴露了对函数缺乏理解。
这是一个函数声明:
function foo(bar) {}
bar 就在那里声明,它是函数的参数。它的值取决于函数的调用方式:
foo(5); // bar will be 5
如果你想问items的值从哪里来,那么答案就是来自数据库,toArray()方法与我在Q2中描述的类似。它需要一个回调并使用正确的值调用它。
关于javascript - Node.js 和 MongoDB 代码澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410123/