我有一个架构:
var photoSchema = new mongoose.Schema({
id: String, // Unique ID identifying this photo
file_name: String,
date_time: {type: Date, default: Date.now},
user_id: mongoose.Schema.Types.ObjectId, // The user id of the user who created the photo.
comments: [commentSchema] // Comment objects representing the comments made on this photo.
});
var Photo = mongoose.model('Photo', photoSchema);
我试图从大多数注释的特定用户那里找到照片。这是我所做的:
Photo.aggregate([
{
$project: {
id: 1,
file_name: 1,
date_time: 1,
user_id: 1,
comments: 1,
length: {$size: "$comments"}
}
},
{
$match: {
user_id: mongoose.Schema.Types.ObjectId(request.params.id)
}
},
{
$sort: { length: -1 }
}
], function (err, info2){
if (err) {
// Query returned an error.
console.error('Doing /user/usage/:id error:', err);
response.status(400).send(JSON.stringify(err));
return;
}
console.log(info2);
finalOutput.most_commented = info2[0];
response.end(JSON.stringify(finalOutput));
});
我只在控制台。log中获得一个空阵列[],我知道$匹配是不起作用的,因为如果我删除$匹配条款,它会给我整个表中带有最大注释的照片。我想根据其用户_id进行过滤并获取属于1个特定用户的照片。
我不明白我在做什么错。我尝试了:
1. $ match:{user_id:mongoose.schema.types.objectid(request.params.id)}
2. $ match:{user_id:request.params.id}
3. $ match:{" user_id":request.params.id}
第一步
const ObjectId = require('mongoose').Types.ObjectId
第二步
{ $match : { _id: ObjectId("606c74d5f9e3f30f8caa3451")} }
ID变量将由"字符串"构建,而不是ObjectId值。猫鼬"自动铸造"objectID的字符串值在常规查询中为其正确的类型,而不是在汇总中。更多详细信息-https://github.com/automattic/mongoose/issues/1399
这就是为什么您需要在代码本身中进行铸造。
{ $match : { _id: mongoose.Types("606c74d5f9e3f30f8caa3451")} }
(不要忘记导入杂种)