【问题标题】:MongoDB, Aggregate $match not working on ObjectIdMongoDB,聚合 $match 不适用于 ObjectId
【发布时间】:2017-08-03 23:57:38
【问题描述】:

我有一个架构是:

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

我正在尝试从具有最多 cmets 的特定用户那里找到照片。这是我所做的:

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

我在 console.log 中只得到一个空数组 [],我知道 $match 不起作用,因为如果我删除 $match 子句,它会为我提供整个表中最大 cmets 的照片。我想根据他们的 user_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}

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

第一步

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

第二步

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

【讨论】:

    【解决方案2】:

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

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

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

    (别忘了导入猫鼬)

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 2013-04-05
      • 2019-03-25
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多