How to return JSON from MongoDB in Node.js?
Solution 1
I was able to answer my question with help from node's native monogodb driver github page: See here.
In essence, what I did was to define my exported function within the MongoClient's connection function. For some reason I thought node exports had to be in the root of the module, but that's not the case. Here's a finished version:
'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();
});
});
And then in another file:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName());
});
Of course, this solution requires that I hardcode queries, but I'm okay with that for now. Will cross that bridge when I come to it.
Solution 2
Found a simple tweak for this. Let say the callback to the findOne returns result then you can convert the result to JSON object like this
result = JSON.parse(JSON.stringify(result))
Now you can access the result and its fields simply with the dot operator.
Solution 3
this may help
var cursor = db.collection('pokemons').find({name:name}).toArray(function(err,arr){
return arr;
});
just another profile name
Updated on July 30, 2020Comments
-
just another profile name almost 4 years
I have a mongodb database called
pokemon
with a collection calledpokemons
. Here is my attempt to write a function that will do afind()
operation in 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? }); };
I then call this function in another file:
var express = require('express'); var router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName('Dratini')); })
This link is helpful in showing how to log mongodb data to the console by doing some sort of
each()
method on the cursor object, but I don't know how toreturn
json through thegetPokemonByName
function. I tried to define an empty array on the root scope of thegetPokemonByName
function and push data into that array with each iteration of the.each
method show in that link, but I think I still can't return that array because it happens after the fact.BTW, I'm really just doing this for fun and to learn about MongoDB and Node.js, so I don't want to use or an ODM like Mongoose to do some of this work for me.