MongoDB,聚合$match未在ObjectId上工作

6

我有一个架构,它是这样的:

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));
        });

控制台中只会得到一个空数组[],我知道$match没有起作用,因为如果我删除$match子句,它会给我整个表中具有最多评论的照片。我想根据用户ID过滤和获取属于特定用户的照片。

我不明白我做错了什么。 我尝试过:
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}


你能看一下这个吗?https://dev59.com/t2Qo5IYBdhLWcg3wG8SE - s7vr
1
原来问题出在 ObjectId 的转换上。它被使用了 mongoose.Schema.Types.ObjectId 这个 Schema 类型进行转换,但实际上只需要使用纯粹的 mongoose.Types.ObjectId 就可以了。 (来源:https://dev59.com/t2Qo5IYBdhLWcg3wG8SE#16312935) - BNKS
昨晚我花了好几个小时在这上面,太傻了!:D - BNKS
@BNKS 看起来非常相似,几乎是重复的,请您自行处理以使网站更加清洁 :) - Abdul Hameed
2个回答

6

第一步


const ObjectId = require('mongoose').Types.ObjectId

第二步


{ $match : { _id: ObjectId("606c74d5f9e3f30f8caa3451")} }

0

Id变量将由“字符串”构成,而不是ObjectId值。在常规查询中,Mongoose会将字符串值自动转换为ObjectId的正确类型,但在聚合中不会。更多细节 - https://github.com/Automattic/mongoose/issues/1399

这就是为什么您需要在代码本身中进行转换的原因。

{ $match : { _id: mongoose.Types("606c74d5f9e3f30f8caa3451")} }

(别忘了导入mongoose)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接