Node.js 如何使用mongo'返回响应;什么是总量?
我从mongodb开始,我使用聚合函数,它给我sampleStatus数组中最后一个元素的最后一个用户。(我是指添加到sampleStatus的最新记录) 我收集了如下样本:Node.js 如何使用mongo'返回响应;什么是总量?,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我从mongodb开始,我使用聚合函数,它给我sampleStatus数组中最后一个元素的最后一个用户。(我是指添加到sampleStatus的最新记录) 我收集了如下样本: { "_id" : ObjectId("58d6cbc14124691cd8154d72"), "correlativeCode" : "CSLLPA53E20M017W", "registrationMethod" : "taken", "originPlace" : "SOMEPLACE
{
"_id" : ObjectId("58d6cbc14124691cd8154d72"),
"correlativeCode" : "CSLLPA53E20M017W",
"registrationMethod" : "taken",
"originPlace" : "SOMEPLACE",
"temperature" : 16,
"sampleStatus" : [
{
"nameStatus" : "status1",
"place" : "place1",
"rejectionReason" : "Nothing",
"user" : "user1",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status2",
"place" : "place2",
"rejectionReason" : "Nothing",
"user" : "user4",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status3",
"place" : "place3",
"rejectionReason" : "Nothing",
"user" : "user3",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status4",
"place" : "place4",
"rejectionReason" : "Nothing",
"user" : "user1",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status5",
"place" : "place5",
"rejectionReason" : "Nothing",
"user" : "user5",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
}
]
}
这是我正在使用的函数:
db.collection.aggregate([
{ "$match": { "correlativeCode": "CSLLPA53E20M017W" } },
{ "$redact": {
"$cond": [
{ "$eq": [
{ "$let": {
"vars": {
"item": { "$arrayElemAt": [ "$sampleStatus", -1 ] }
},
"in": "$$item.user"
} },
"user5"
] },
"$$KEEP",
"$$PRUNE"
]
}}
])
当我在mongodb的控制台中使用它时,它是有效的。。但是,当我尝试在controller.js中调整它时
VerifySample: function (req, res) {
var id = req.body.idSample;
var idUser=req.body.currentuser;
SamplePatientModel.aggregate([
{ $match: { _id: id } },
{ $redact: {
$cond: [
{ $eq: [
{ $let: {
vars: {
"item": { $arrayElemAt: [ "$sampleStatus", -1 ] }
},
in: "$$item.user"
} },
idUser
] },
"$$KEEP",
"$$PRUNE"
]
}}
],
function(err, _SamplePatient) {
console.log('entry function');
if (err) {
console.log('Entry err');
return res.status(500).json({message: 'Error SamplePatient', error: err});
}
//No results
if(!_SamplePatient){
console.log('no results ');
return res.status(404).json({message: 'error', error: err});
}
console.log('Got it');
console.log(_SamplePatient);
return res.status(200).json(_SamplePatient);
}
);}
我的回应如下:
[]
console.log(\u SamplePatient)
不显示任何内容
“进入功能”字样打印在控制台中
我做错了什么
请帮帮我
谢谢。聚合管道不支持mongoose中的Casting
ObjectId
因此,必须在聚合管道中将字符串值显式转换为ObjectId
更新你的比赛阶段到下面
{$match:{{u id:mongoose.Types.ObjectId(req.body.idSample)}}
问题就在这里
猫鼬文件:
非常感谢@veeram