// Use connect method to connect to the server
MongoClient.connect('mongodb://localhost:27017/products', function (err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
var findDocuments = function (db, callback) {
// Get the documents collection
var collection = db.collection('products');
// Find some documents
collection.find(
{ $and: [{
"qty": {
$gt: 0
}
}, {
"price": {
$gte: 2000.0
}
}]
},
{ "name": 1,
"brand": 1,
"_id": 0
}).toArray(function (err, docs) {
assert.equal(err, null);
console.log('Found docs');
callback(docs);
db.close();
});
}
});
function callback(docs) {
console.log('callback called');
console.log(docs)
}
我得到Connected successfully to server
然后什么都没有,没有输出甚至是错误。我做错了什么?
答案 0 :(得分:2)
你缺少调用函数
findDocuments(db, callback);
功能应该是这样的:
MongoClient.connect('mongodb://localhost:27017/products', function (err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
var findDocuments = function (db, callback) {
// Get the documents collection
var collection = db.collection('products');
// Find some documents
collection.find(
{
$and: [{
"qty": {
$gt: 0
}
}, {
"price": {
$gte: 2000.0
}
}]
},
{
"name": 1,
"brand": 1,
"_id": 0
}).toArray(function (err, docs) {
assert.equal(err, null);
console.log('Found docs');
callback(docs);
db.close();
});
}
findDocuments(db, callback);
});