Javascript 重塑来自mongodb的结果
在node.js应用程序中,我将mongodb与mongoose驱动程序一起使用。如何重塑Modell.find操作的结果?如果我得到这样的示例文档:Javascript 重塑来自mongodb的结果,javascript,node.js,mongodb,mongoose,aggregation-framework,Javascript,Node.js,Mongodb,Mongoose,Aggregation Framework,在node.js应用程序中,我将mongodb与mongoose驱动程序一起使用。如何重塑Modell.find操作的结果?如果我得到这样的示例文档: { _id: ObjectId(...), score: 14, time: 123 } [{ index: 0 player: ObjectId // _id field renamed to player score: 14, time: 123 }, { index:
{
_id: ObjectId(...),
score: 14,
time: 123
}
[{
index: 0
player: ObjectId // _id field renamed to player
score: 14,
time: 123
},
{
index: 1
player: ObjectId // _id field renamed to player
score: 6,
time: 321
},
...
{
index: N
player: ObjectId // _id field renamed to player
score: 1,
time: 456
}
]
在我的查找操作中,我想在结果上添加一个索引计数器。查找并重命名_id字段。这可能吗
如果希望我的文档流看起来像这样:
{
_id: ObjectId(...),
score: 14,
time: 123
}
[{
index: 0
player: ObjectId // _id field renamed to player
score: 14,
time: 123
},
{
index: 1
player: ObjectId // _id field renamed to player
score: 6,
time: 321
},
...
{
index: N
player: ObjectId // _id field renamed to player
score: 1,
time: 456
}
]
我试过了
Modell.find({}, {player: '$_id', score: 1, time: 1})
.exec(function(err, players) {
...
});
但是_id字段不会在结果文档流中重命名。这可能吗?以及如何在文档流中创建文档计数器。find方法不会进行这种重命名。为此,您需要聚合框架和操作符
不过,文档上的索引号完全是另一回事,尽管我不明白为什么需要这样做,因为这些索引值已经可以访问该数组,但在从服务器检索该数组后,您将更改结果
Model.aggregate(
[
{ "$project": {
"_id": 0,
"player": "$_id",
"score": 1,
"time": 1,
}},
],
function(err,results) {
if (err) throw err;
results = results.map(function(x,index) { x.index = index; return x; });
console.log(results);
}
);
实际上,如果您只想返回整个结果,您可以使用map完成整个操作:
Model.find({},function(err,result) {
if (err) throw err;
results = results.map(function(x,index) {
x.index = index;
x.player = x._id;
delete x._id;
return x;
});
console.log(results);
});
如果我在聚合中需要搜索查询,我应该将搜索查询放在哪里?与Model.find{score:10}相同…请参见文档中的。实际上,您可以使用“查找偶数”并重塑整个结果。您不必担心在这里迭代光标。