【问题标题】:node js how to assign two collection data into a single object to render on viewsnode js如何将两个集合数据分配到一个对象中以在视图上呈现
【发布时间】:2017-10-08 22:19:19
【问题描述】:

我正在为自己的实践创建一个简单的新闻文章应用程序。所以我在猫鼬中创建了两个模式来执行此操作。
现在我正在尝试从这些集合中检索数据并尝试将这些值分配给单个对象。
我尝试了很多次并搜索了很多地方,但仍然无法在 node js 中找到更好的解决方案。

这是我用来在视图上显示数据的路由器:

app.get('/admin-area345', function(req, res){
    articles.find({}, function(err, data){
        if(err) throw err;
        for (var i = 0; i < data.length; i++) {
            categories.findById(data[i].cat_id).then(function(cates){
                data[i]['cat_name'] = cates.catName;
                console.log(data);
                res.render('pages/admin/index', {
                    arts: data
                });
            });
        }
    });
}); 

这是我的类别模型架构:

const catSchema = Schema({
    catName: {
        type: String
    }
});

这是我的文章架构:

const artSchema = Schema({
    title: {
        type: String
    },
    body: {
        type: String
    },
    author: {
        type: String
    },
    cat_id: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

最后,这是显示从 mongoose 集合中检索到的数据的视图页面。为此,我使用 EJS 模板作为我的视图引擎。

<%if(typeof(arts) != 'undefined'){%>
<div class="articles">
<%for(var i = 0; i < arts.length; i++){%>
    <h2><%=arts[i].title%> | <small><%=arts[i].cat_name%></small></h2>
    <p><%=arts[i].body%></p>
    <p>Added date - <%=arts[i].date%></p>
    <small>Added By - <%=arts[i].author%></small></br>
    <a href="/admin-area345/adminupdateart">Update Article</a></br>
    <a href="/admin-area345/admindelart">Delete Article</a></br>
<%}%>
</div>
<%}%>

希望你们能给我一个更好的答案,让我轻松做到这一点。

【问题讨论】:

    标签: node.js express mongoose ejs


    【解决方案1】:

    您应该使用聚合进行查询,然后您可以轻松地修改您的对象。所以试试这个:: 当我们使用 find 查询从 mongodb 检索数据时,我们无法更新或更改对象。所以使用聚合而不是 find()。

    app.get('/admin-area345', function(req, res){
        articles.aggregate([{'$match':{}]).exec(function(err, data){
            if(err) throw err;
            for (var i = 0; i < data.length; i++) {
                categories.findById(data[i].cat_id).then(function(cates){
                    data[i]['cat_name'] = cates.catName;
                    console.log(data);
                    res.render('pages/admin/index', {
                        arts: data
                    });
                });
            }
        });
    }); 
    

    【讨论】:

    • 感谢您的回答,但请您向我解释一下代码。那行是否意味着'articles.aggregate([{'$match':{}])'@vipin sharma
    • 当你从文章集合中检索数据时,你得到的数据比你得到的数据[对象数组]。如果你想修改数据对象“数据[i]['cat_name'] = cates.catName;”比你想在你的数据对象上添加“['cat_name]'”字段。但是你不能修改这个。所以如果你使用聚合查询而不是找到数据[对象数组]而不是轻松修改这个。但我不知道是什么聚合查询和查找查询数据[]数组的区别。所以检查聚合查询。
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多