在开始使用聚合来创建文档的时间戳之前,我使用 findOne 这样我可以获得单个对象,但现在我得到一个包含单个对象的数组。是否可以使查询返回单个对象而不是数组?先感谢您。
我正在使用的查询:
News.aggregate()
.match({ '_id': n })
.project({ 'title': true, 'text': true, 'timestamp': { '$subtract': ['$date', new Date('1970-01-01')] } })
返回的是什么:
[
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
]
我希望得到的回报:
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
Aggregate
方法返回一个数组;这是定义的行为。如果您想让这种行为适应您的方式,您可以重新创建自己的聚合函数;或在每次调用时处理数组;喜欢 :
async function aggregate(model, func) {
const aggregateObject = func(News.aggregate());
const ret = await aggregateObject.exec();
// Deal with the fact there is no answer
if (ret && ret.length) {
return ret[0];
}
return false;
}
const directData = await aggregate(News, (aggregateObj) => {
return aggregateObj
.match(...)
.project(...);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)