使用mongoose model.find()获取只有1个字段的所有条目 [英] use mongoose model.find() to get all entries of only 1 field

查看:77
本文介绍了使用mongoose model.find()获取只有1个字段的所有条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试使用不同的model.find()变体,但没有人做我想要的。

I've tried to use different variation of model.find(), but none do what I want.

以下代码是我正在使用的代码,但它显示每个字段,我只想要iframe字段。

code below is what I'm working with, but it displays every single field, and I only want the "iframe" field.

app.get('/api/videos', function (req, res) {
    Video.find({}, function (err, docs) {
       res.json(docs);
    });
});

以下代码确实有效,我只获得'iframe'字段,但它会反转json输出和我不希望这样。它也获得了独特的价值,即使它并不重要,因为每个条目都是唯一的。

Code below does work and I only get the 'iframe' field, but it reverses the json output and I don't want that. It also get unique values, even though it's not that important since every entry is unique.

app.get('/api/videos', function (req, res) {
    Video.find().distinct('iframe', function (err, docs) {
        res.json(docs);
    });
});

W

推荐答案

您要找的是投影

Video.find({}, {iframe: 1}, function (err, docs) {
   res.json(docs);
});

find 函数的第二个参数告诉返回哪个字段。如果你不想要 _id ,那么使用: {_ id:0,iframe:1}

The second parameter to the find function tells which field to return. If you do not want the _id as well, then use: {_id:0, iframe:1}

如下所示:

Video.find({}, {_id:0, iframe:1}, function (err, docs) {
   res.json(docs);
});






然而,投影不会给你不同的值。它只返回你想要使用的字段(以及重复)。


However, projection does not give you distinct values. It only returns the fields you want to use (along with repetitions).

这篇关于使用mongoose model.find()获取只有1个字段的所有条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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