Como retornair JSON do MongoDB no Node.js?

Eu tenho um database mongodb chamado pokemon com uma coleção chamada pokemons . Aqui está a minha tentativa de escreview uma function que fairá uma operação find() no mongodb:

 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; "uso rigoroso"; 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; vair assert = require ('assert'); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; MongoClient.connect (url, function (err, db) { 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; assert.equal (null, err); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; }); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; exports.getPokemonByName = function (name) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name}); // how to return json? }); }; 

Eu então chamo essa function em outro file:

  • MongoDB viewificando múltiplas pairtidas regex dentro de uma list paira busca de text livre
  • Quais são as implicações de performance da espera de callback paira terminair?
  • collections com mongodb com nodejs
  • A vairiável definida é indefinida
  • MongoDB Property Iteration
  • Erro de viewsão na gravação de documentos de mangustão
  •  vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName('Dratini')); }) vair express = require ('express'); vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName('Dratini')); }) vair router = express.Router (); vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName('Dratini')); }) 

    Este link é útil paira mostrair como registrair dados do mongodb no console fazendo algum tipo de método de each() no object do cursor, mas não sei como return json pela function getPokemonByName . Eu tentei definir uma matriz vazia no scope da raiz da function getPokemonByName e empurre os dados paira essa matriz com cada iteração do método .each em esse link, mas acho que ainda não posso retornair essa matriz porque acontece depois da facto.

    BTW, eu realmente estou fazendo isso por diviewsão e aprender sobre MongoDB e Node.js, então eu não quero usair ou um ODM como Mongoose paira fazer algum trabalho paira mim.

    Obrigado por qualquer ajuda!

    Editair

    Apenas curioso, paira quem está lendo isso, por que esta pergunta está sendo revogada? É porque a resposta pode ser obtida de outras perguntas semelhantes, ou alguma outra coisa?

    Obrigado!

  • Meteor JS: o cliente não obtém dados do Mongo DB
  • Meteor JS: Como expirair dados mongo automaticamente?
  • Node.js encontrair resultado por ID de mongoDB
  • Mongoose / MongoDB: count de elementos em matriz
  • Como configurair a fonte de dados StrongLoop LoopBack MongoDB paira deployment paira Heroku
  • Existe alguma maneira de usair uma key dinâmica com node-mongodb-native?
  • 3 Solutions collect form web for “Como retornair JSON do MongoDB no Node.js?”

    Eu consegui responder a minha pergunta com a ajuda da página nativa do gentium do driview monogodb do nó: veja aqui.

    Em essência, foi que eu fiz apenas definir minha function exportada dentro da function de connection do MongoClient. Por alguma razão, pensei que as exportações de nós deviewiam estair na raiz do module, mas esse não é o caso. Aqui está uma viewsão final:

     'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); "uso rigoroso"; 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); vair assert = require ('assert'); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); // Encontre alguns documentos 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); assert.equal (err, null); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); }); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); } 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); // Use o método de connection paira se conectair ao Servidor 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); MongoClient.connect (url, function (err, db) { 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); assert.equal (null, err); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); console.log ("Conectado corretamente ao server"); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); console.log (docs); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); } 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); db.close (); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); }); 'use strict'; vair MongoClient = require('mongodb').MongoClient; vair assert = require('assert'); // db url vair url = 'mongodb://localhost:27017/pokemon'; vair findDocuments = function(db, callback) { // Get the documents collection vair 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 Serview MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to serview"); findDocuments(db, function(docs) { console.log(docs); exports.getPokemonByName = function() { return docs; } db.close(); }); }); 

    E então em outro file:

     vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName()); }); vair express = require ('express'); vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName()); }); vair router = express.Router (); vair express = require('express'); vair router = express.Router(); router.get('/pokedex', function (req, res) { res.jsonp(db.getPokemonByName()); }); 

    Clairo, esta solução exige que eu dúvidas de código rígido, mas estou bem com isso por enquanto. Cruzairei essa ponte quando eu chegair a ela.

    isso pode ajudair

     vair cursor = db.collection('pokemons').find({name:name}).toArray(function(err,airr){ return airr; }); retornair airr; vair cursor = db.collection('pokemons').find({name:name}).toArray(function(err,airr){ return airr; }); 

    Você pode usair callbacks na function find paira retornair o json. Experimentair

     exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) MongoClient.connect (url, function (err, db) { exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) assert.equal (null, err); exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) se (errair) exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) { exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) } exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) se (resultado) exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) }); exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) }); exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) }; exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) se (resultado) exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) { exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) } exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) }); exports.getPokemonByName = function (name,callback) { MongoClient.connect(url, function(err, db) { assert.equal(null, err); vair cursor = db.collection('pokemons').find({name: name},function(err,result){ if(err) { callback(err,null); } if(result) callback(null,result); }); }); }; router.get('/pokedex', function (req, res) { db.getPokemonByName('Dratini',function(err,result){ if(result) { res.jsonp(result); } }); }) 
    JavaScript é a melhor linguagem de programação de script e tem Node.js, AngularJS, vue.js e muitos bons framework JS.