Javascript 使用express mongo显示类别
我有一个mongo的数据,就像 根 chi1: chi2 chi11Javascript 使用express mongo显示类别,javascript,node.js,mongodb,express,pug,Javascript,Node.js,Mongodb,Express,Pug,我有一个mongo的数据,就像 根 chi1: chi2 chi11 {'id':id1,'name':'chi11','child'=['id111','id112','id113']} 现在我想在模板中显示类别,如下所示: root.name->chi1.name->chi11.name ->chi2.name 如果我们可以从父项查询子项 您可以尝试以下查询:- db.collName.find({_id : {$in:['id1','id2','i
{'id':id1,'name':'chi11','child'=['id111','id112','id113']}
现在我想在模板中显示类别,如下所示:
root.name->chi1.name->chi11.name
->chi2.name
如果我们可以从父项查询子项 您可以尝试以下查询:-
db.collName.find({_id : {$in:['id1','id2','id3']}}).toArray(function(err, results){
console.log(results); //Will give you array of child results.
})
现在,您可以在结果数组中循环并获得相应的子元素名称
请在查询中参阅了解如何在中使用$
编辑:-
使用以下内容:-
function getResults(id, callback)
{
db.collection.find({_id : parentId}).toArray(function(err, pres)
{
db.collName.find({_id : {$in:pres[0].child}}).toArray(
function(err, results){
console.log(results); //Will give you array of child results.
console.log(pres[0]); // Result of root;
callback(err, results, pres) ; //Return all the results
})
});
}
希望这对您有所帮助。
使用mongoose 4.0填充是查询子对象的最佳解决方案
您能告诉我们您到目前为止都做了哪些尝试吗?而且你的问题也不够清楚。作为这个问题的数据:我试图将root传递给template,但我不知道如何从数据库中查询chi1.name等子信息,chi11.name在模板上显示。我使用了mongoose,我们可以通过ID从db中查询对象,但问题是如果我只将根传递给模板,我无法获取子对象的信息,例如要在模板中显示的名称,因为在根对象中,我们只知道子对象的ID…所以我们必须再次返回控制器进行查询,用翡翠模板是不可能的。你到底想做什么?在您的情况下,您必须查询两次。没有其他选择。您可以在一个函数中执行这两个查询,然后将所有结果发送回并使用。
root.name->chi1.name->chi11.name
->chi2.name
db.collName.find({_id : {$in:['id1','id2','id3']}}).toArray(function(err, results){
console.log(results); //Will give you array of child results.
})
function getResults(id, callback)
{
db.collection.find({_id : parentId}).toArray(function(err, pres)
{
db.collName.find({_id : {$in:pres[0].child}}).toArray(
function(err, results){
console.log(results); //Will give you array of child results.
console.log(pres[0]); // Result of root;
callback(err, results, pres) ; //Return all the results
})
});
}