我有一个名为Pokemon
的mongodb数据库,其中包含一个名为Pokemons
的集合。下面是我编写一个函数的尝试,该函数将在MongoDB中执行find()
操作:
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// db url
var url = 'mongodb://localhost:27017/pokemon';
exports.getPokemonByName = function (name) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('pokemons').find({name: name});
// how to return json?
});
};
然后我在另一个文件中调用此函数:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName('Dratini'));
})
此链接有助于展示如何通过对cursor对象执行某种eace()
方法将mongodb数据记录到控制台,但我不知道如何通过GetPokeMonbyName
函数返回
json。我试图在GetPokemonByName
函数的根作用域上定义一个空数组,并在的每次迭代中将数据推入该数组。每个
方法都显示在该链接中,但我认为我仍然无法返回该数组,因为它发生在事实之后。
顺便说一下,我真的只是为了好玩和了解MongoDB和Node.js,所以我不想使用或像Mongoose这样的ODM来为我做一些这方面的工作。
我能够在Node的原生monogodb驱动程序github页面的帮助下回答我的问题:参见此处。
本质上,我所做的是在MongoClient的连接函数内定义我导出的函数。出于某种原因,我认为节点导出必须在模块的根中,但事实并非如此。下面是一个完成的版本:
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// db url
var url = 'mongodb://localhost:27017/pokemon';
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('pokemons');
// Find some documents
collection.find({name: 'Dratini'}).toArray(function(err, docs) {
assert.equal(err, null);
// assert.equal(2, docs.length);
console.log("Found the following records");
callback(docs);
});
}
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
findDocuments(db, function(docs) {
console.log(docs);
exports.getPokemonByName = function() {
return docs;
}
db.close();
});
});
然后在另一个文件中:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName());
});
当然,这个解决方案要求我对查询进行硬编码,但我现在可以接受这一点。当我到达那座桥时,我将会过那座桥。
找到了一个简单的解决办法。假设对findOne的回调返回结果,那么您可以将结果转换为JSON对象,如下所示
result=json.parse(json.stringify(result))
现在,您可以简单地使用点运算符访问结果及其字段。
这可能会有帮助
var cursor = db.collection('pokemons').find({name:name}).toArray(function(err,arr){
return arr;
});