jus*_*ame 6 javascript database json mongodb node.js
我有一个mongodb数据库,调用pokemon了一个名为的集合pokemons.这是我尝试编写一个将find()在mongodb中执行操作的函数:
'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?
});
};
Run Code Online (Sandbox Code Playgroud)
然后我在另一个文件中调用此函数:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName('Dratini'));
})
Run Code Online (Sandbox Code Playgroud)
此链接有助于显示如何通过each()对游标对象执行某种方法将mongodb数据记录到控制台,但我不知道如何return通过该getPokemonByName函数进行json .我试图在getPokemonByName函数的根作用域上定义一个空数组,并将数据推送到该数组中,.each方法的每次迭代都显示在该链接中,但我认为我仍然无法返回该数组,因为它发生在事实之后.
顺便说一句,我真的只是为了好玩并了解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();
});
});
Run Code Online (Sandbox Code Playgroud)
然后在另一个文件中:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName());
});
Run Code Online (Sandbox Code Playgroud)
当然,这个解决方案要求我对查询进行硬编码,但我现在对此感到满意.当我来到它时,会越过那座桥.
小智 5
为此找到了一个简单的调整。假设 findOne 的回调返回结果,那么您可以将结果转换为 JSON 对象,如下所示
结果 = JSON.parse(JSON.stringify(结果))
现在您只需使用点运算符即可访问结果及其字段。
| 归档时间: |
|
| 查看次数: |
15534 次 |
| 最近记录: |