簡體   English   中英

如何在節點JS MEAN堆棧中使用Mongodb查詢

[英]How do I work with Mongodb Queries in a node JS MEAN stack

我正在使用linnovate MEAN樣板構建應用程序: https : //github.com/linnovate/mean

使用MongoDB,我了解了如何在數據庫上查詢集合並通過命令行獲取結果,例如:

db.articles.find({ 'title' : 'hello world'})

在MEAN應用中,我注意到的這種類型的查詢區域位於app/controllers/articles.js文件中:

/**
* List of Articles
*/
exports.all = function(req, res) {
    Article.find().sort('-created').populate('user', 'name username').exec(function(err, articles) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        }
    });
};

如果我想添加一種返回帶有特定查詢的另一個列表的方法,我將如何處理呢?這是我正在處理的代碼:

exports.all = function(req, res) {
    Article.find().sort('-created').populate('user', 'name username').exec(function(err, articles) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        Article.find({ 'category' : 'hello world').sort('-created').populate('user', 'name username').exec(function(err, morearticles) {
            if (err) {
                res.render('error', {
                    status: 500
                });
            } else {
                res.jsonp(morearticles);
            }
        });
        }
    });
};

由於其異步特性,您必須將第二個查詢放在第一個查詢的else-statement中。

請參閱以下問題以獲取更多信息:

將多個數據庫/貓鼬查詢的結果呈現到express.js中的視圖

Mongoose Express中的兩個數據庫查詢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM