简体   繁体   中英

How to query a Mongo with Node.js?

I realize this sounds like a completely redundant question, but just hear me out.

Eventually I'd like to query MongoDB from the dom, but until then I'm okay with doing from my routes module. Here is my query:

var db = require('./config/db.js');

router.get('/test', function (req, res) {
  res.jsonp(db.getData('sampleSet'));
});

'sampleSet' is the name of the collection I'm querying. The getData function is supposed to get data from MongoDB. I'm putting it in the callback of MongoClient's connect function because I can't figure any other way. From my point of view, since getData() is returning a function with a callback, findData , it should return the data. But it doesn't. The console.logs return the data, but it must be returning undefined.

function findData (db, c, callback) {
  var collection = db.collection(c);
  collection.find().toArray(function(err, docs) {
    assert.equal(err, null);   
    callback(docs);
  });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(err, null);
  console.log('CONNECTED CORRECTLY TO SERVER.');
  exports.getData = function(c) {
    return 
    findData(db, c, function(docs) {
      console.log('FOUND THE FOLLOWING RECORDS: ');
      return docs;
      db.close();
    });
  }
});

If var db = require('./config/db.js'); is your schema, and 'sampleSet' is collection name , Then you can get the data using this

 router.get('/test', function (req, res) { db.sampleSet.find({},function(err,data){ if(err) throw err; else res.send(data) }); }); 

but for this you have to write your db.js file in this way

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var sampleSetSchema = new Schema({ //Your schemas goes here.. // fields : types // .. // .. }, { collection: "sampleSet" // collection name }); // // Export the Mongoose model var SampleSet = mongoose.model('SampleSet', sampleSetSchema); module.exports = { SampleSet: SampleSet } 

Your findData method is not returning anything.

It is passing docs to callback and callback is returning docs again to findData method. But there is no return from findData .

So if findData is not returning anything, getData is not going to return anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM