简体   繁体   English

如何使用Node.js查询Mongo?

[英]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. 最终,我想从dom中查询MongoDB,但在那之前,我可以通过自己的routes模块进行查询。 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. “ sampleSet”是我正在查询的集合的名称。 The getData function is supposed to get data from MongoDB. 应该使用getData函数从MongoDB获取数据。 I'm putting it in the callback of MongoClient's connect function because I can't figure any other way. 我把它放在MongoClient的connect函数的回调中,因为我找不到其他方法。 From my point of view, since getData() is returning a function with a callback, findData , it should return the data. 从我的角度来看,由于getData()返回带有回调的函数findData ,因此它应该返回数据。 But it doesn't. 但事实并非如此。 The console.logs return the data, but it must be returning undefined. console.logs返回数据,但必须返回未定义的数据。

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'); 如果var db = require('./config/db.js'); is your schema, and 'sampleSet' is collection name , Then you can get the data using this 是您的架构, 'sampleSet'是集合名称,则可以使用此数据

 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 但是为此,您必须以这种方式编写db.js文件

 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. 您的findData方法不返回任何内容。

It is passing docs to callback and callback is returning docs again to findData method. 它是通过docscallbackcallback将返回docs再次findData方法。 But there is no return from findData . 但是findData没有返回。

So if findData is not returning anything, getData is not going to return anything. 因此,如果findData不返回任何内容,则getData将不返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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