use mongoose model.find() to get all entries of on

2019-03-03 16:35发布

问题:

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

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

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

回答1:

What you are looking for is called projection:

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

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}

Like so:

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



回答2:

You can use the projection parameter to specify which field you would like to include in the result.

db.collection.find(query, projection)

If find() includes a projection argument, the matching documents contain only the projection fields and the _id field. You can optionally exclude the _id field.

The projection parameter takes a document of the following form:

{ field1: <boolean>, field2: <boolean> ... }

The <boolean> value can be any of the following:

1 or true to include the field. The find() method always includes the _id field even if the field is not explicitly stated to return in the projection parameter.

0 or false to exclude the field.

When you include a field you can only explicitly exclude fields in the case of the _id field.

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