猫鼬-获取模型中数组的长度 [英] Mongoose - get length of array in model

查看:80
本文介绍了猫鼬-获取模型中数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Mongoose模式:

I have this Mongoose schema:

var postSchema = mongoose.Schema({

    postId: {
        type: Number,
        unique: true
    },

    upvotes: [
        {
            type: Number,
            unique: true
        }
    ]

});

什么是获取upvotes数组长度的最佳查询?我不认为我需要使用聚合,因为我只想查询一个模型,只需要给定模型的upvotes数组的长度即可.

what the best query to use to get the length of the upvotes array? I don't believe I need to use aggregation because I only want to query for one model, just need the length of the upvotes array for a given model.

真的很难在网上找到此信息-我搜索的所有内容都提到了我认为不需要的汇总方法.

Really struggling to find this info online - everything I search for mentions the aggregation methodology which I don't believe I need.

此外,请注意,upvotes数组的唯一架构属性不起作用,也许我做错了.

Also, as a side note, the unique schema property of the upvotes array doesn't work, perhaps I am doing that wrong.

推荐答案

find结果只能包含来自文档本身的内容 1 ,而aggregate可以投影从其派生的新值文档的内容(如数组的长度).这就是为什么即使只得到一个文档,也需要使用aggregate的原因.

find results can only include content from the docs themselves1, while aggregate can project new values that are derived from the doc's content (like an array's length). That's why you need to use aggregate for this, even though you're getting just a single doc.

Post.aggregate([{$match: {postId: 5}}, {$project: {upvotes: {$size: '$upvotes'}}}])

1 唯一的例外是 $meta 投影运算符,用于投影$text查询结果的分数.

1Single exception is the $meta projection operator to project a $text query result's score.

这篇关于猫鼬-获取模型中数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆