繁体   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