简体   繁体   English

Node.js模块从MongoDB数据库中获取数据

[英]Node.js module to fetch data from MongoDB database

I want to use an module to get and process data from my MongoDB database. 我想使用一个模块从MongoDB数据库中获取和处理数据。 (It should generate an object that represents my Express.js site's navbar) (它应该生成一个表示我的Express.js网站的导航栏的对象)

I thought of doing something like this: 我想到做这样的事情:

var nav = { Home: "/" };
module.exports = function() {
  MongoClient.connect(process.env.MONGO_URL, function(err, db) {
    assert.equal(err, null);
    fetchData(db, function(articles, categories) {
      combine(articles, categories, function(sitemap) {
        // I got the data. What now?
        console.log("NAV: ", nav);
      })
    });
  });
};

var fetchData = function(db, callback) {
  db.collection('articles').find({}).toArray(function(err, result) {
    assert.equal(err);
    articles = result;
    db.collection('categories').find({}).toArray(function(err, result) {
      assert.equal(err);
      categories = result;
      db.close();
      callback(articles, categories);
    });
  });
};

var combine = function(articles, categories, callback) {
  categories.forEach(function(category) {
    nav[category.title] = {};
    articles.forEach(function(article) {
      if(article.category == category.name) {
        nav[category.title][article.title] = "link";
      }
    })
  });
  callback(nav);
};

As of line 6, I do have all data I need. 从第6行开始,我确实拥有所需的所有数据。

(An object, currenty like { Home: '/', Uncategorized: { 'Hello world!': 'link' } } ) (一个对象,当前类似于{ Home: '/', Uncategorized: { 'Hello world!': 'link' } } ))

But since I'm in an anonymous function, I don't know how to return that value. 但是由于我处于匿名函数中,所以我不知道如何返回该值。 I mean, return would just return it the function that called it... And in the end, MongoClient.connect would receive my data. 我的意思是, return只会返回调用它的函数...最后,MongoClient.connect将接收我的数据。

If I set a variable instead, it would be set as module.exports returned before Node can even query the data from the database, right? 如果我改为设置一个变量,它将设置为module.exports在Node甚至可以从数据库查询数据之前返回,对吗?

What can I do in order to make this work? 为了使这项工作我该怎么办?

It should result in some kind of function, like 它应该导致某种功能,例如

var nav = require('nav');
console.log(nav());

Thanks in advance! 提前致谢!

You can use mongoose module or monk module. 您可以使用猫鼬模块或僧侣模块。 These modules have been tested properly . 这些模块已正确测试。

Just use 只需使用

npm install mongoose or monk npm安装猫鼬或和尚

Add another callback: 添加另一个回调:

var nav = { Home: "/" };
module.exports = function(cb) {
    MongoClient.connect(process.env.MONGO_URL, function(err, db) {
        assert.equal(err, null);
        fetchData(db, function(articles, categories) {
            combine(articles, categories, function(sitemap) {
                cb(sitemap);
            })
        });
    })
});

And then use this way: 然后使用这种方式:

var nav = require('nav');
nav(function(sitemap){ console.log(sitemap); });

The suggestion about mongoose is great and you can look into it, however I think you've already done the job with the fetching of the data from the db. 关于猫鼬的建议很好,您可以研究一下,但是我认为您已经完成了从数据库中获取数据的工作。 You just need to access it in your main node flow. 您只需要在主节点流中访问它即可。

You can try this: 您可以尝试以下方法:

module.exports.generateNav = function() {
  MongoClient.connect(process.env.MONGO_URL, function(err, db) {
    assert.equal(err, null);
    var output = fetchData(db, function(articles, categories) {
      combine(articles, categories, function(sitemap) {

      })
    });
    return (output);
  });
};

And then in your main application you can call it in the following way: 然后,可以在主应用程序中通过以下方式调用它:

var nav = require('nav');
navigation = nav.generateNav();
console.log(navigation);

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

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