【发布时间】:2016-08-17 13:01:36
【问题描述】:
您好,我正在学习 mongodb 和 nodejs。我成功检索了订单的所有集合。下面是输出
The orders: { __v: 0,
nonmeat: 'pineapple',
meat: 'Bacon',
sauce: 'AlfredoSauce',
crust: 'medium',
_id: 571c1b9aed52d5e5462b99f9 },{ __v: 0,
nonmeat: 'pineapple',
meat: 'Bacon',
sauce: 'AlfredoSauce',
crust: 'medium',
_id: 571c1bba07f035e646d24aa8 },{ __v: 0,
nonmeat: 'parmesan,olives',
meat: 'Salami',
sauce: 'MarinaraSauce',
crust: 'large',
_id: 571c1e3c28dd30ed469eb6df },{ __v: 0,
nonmeat: 'parmesan,olives',
meat: 'Salami',
sauce: 'MarinaraSauce',
crust: 'large',
_id: 571c1f11ba02d9f646f4c5c0 }
但我想将其转换为 javascript 数组,因为该集合返回一个对象数组。我想过滤掉__v 和_id。我打算用这个结果显示在谷歌饼图上。我只想要关键项目:nonmeat、meat、sauce 和 crust。我打算在谷歌饼图上显示一定百分比的项目。
以下是我从 mongodb 检索数据的代码:
app.get('/orders', function(req, res){
var allorders = [];
//get all orders
PizzaOrder.find({}, function(err, orders){
if(err) throw err;
console.log('The orders '+orders.length);
//this is wrong
for(var i=0; i<orders.length;i++) {
allorders.push(JSON.parse(orders[i]));
}
});
console.log('Orders retrieved '+ allorders);
res.json(allorders);
});
更新!!!!!!!!!
我能够以 json 格式发送它并在浏览器上查看。这是我的代码:
app.get('/orders', function(req, res){
//get all orders
PizzaOrder.find({}, function(err, orders){
if(err) throw err;
console.log('The orders '+orders.length);
res.send(orders);
});
});
但我想将其过滤掉 _id: 和 __v:。我正在使用 ajax 调用来接收响应并打算在谷歌饼图上显示。
【问题讨论】:
-
你使用的是哪个 Mongodb API
-
我用过 mongoose 和 mongolab
-
不是副本中公认的答案,而是显示
.toObject()的答案,因为您需要对可以操作的对象执行此操作。但在投影中排除字段也可以。 -
@BlakesSeven 请你举个例子
-
@user3497437 请提供预期的输出。