Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, Select a specific field with find

I'm trying to select only a specific field with

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

But in my json response i'm receiving also the _id, my document schema only has two fiels, _id and name

[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]

Why???

like image 206
TlonXP Avatar asked Oct 16 '22 07:10

TlonXP


People also ask

What does find () return in Mongoose?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

What does select do in Mongoose?

What is select() in Mongoose? select() is a method of Mongoose that is used to select document fields that are to be returned in the query result. It is used to include or exclude document fields that are returned from a Mongoose query. The select() method performs what is called query projection.

How does find work in Mongoose?

The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).

How do you use Find one and delete in Mongoose?

Mongoose | findOneAndDelete() FunctionThe findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.


1 Answers

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};
like image 127
Neil Lunn Avatar answered Oct 20 '22 06:10

Neil Lunn