Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose returning all fields regarding schema

I'm having a collection in my database called businesses. What I want to do is query the database and specific fields, defined in my schema, and not all the fields of the document. I thought that's the reason why the schema exists in the first place ?

Schema

var businessSchema = new mongoose.Schema({
    custom_id: String,
    name: String
});

module.exports = mongoose.model('Business', businessSchema);

Express

router.get('/query', function (req, res, next) {
    res.type('json');
    Business.find({custom_id: req.query.custom_id})
        .then(function (data) {
            res.send({data: data});
        }).catch(function (err) {
        return next(new Error(err.message || err));
    })
});

Response

{
   "data":[
      {
         "_id":"5a50ac105a0d8452b0e341e5",
         "custom_id":"1",
         "name":"Dave and Jane",
         "status":"active",
         "verified":true,
         "created":1492727550760,
         "email":{
            "address":"[email protected]"
         }
      }
   ]
}

In the schema I have only custom_id and name, but whatever fields I define (or I don't), all the fields of the documents are returned when Business.find executes.

Same behavior as if the schema was empty, thus, returning all fields.

like image 214
Andrew Avatar asked Oct 24 '25 10:10

Andrew


2 Answers

In the select function just set the fields you want as 1 and the ones you don't want as 0. See below:

router.get('/query', function (req, res, next) {
    res.type('json');
    Business.find({custom_id: req.query.custom_id}).select({ "name": 1, "_id": 0})
        .then(function (data) {
            res.send({data: data});
        }).catch(function (err) {
        return next(new Error(err.message || err));
    })
});
like image 83
dasersoft Avatar answered Oct 27 '25 01:10

dasersoft


You can also use just "string" to tell which fields to fetch and which to exclude

Business.find().select("name status")

👆 this tells mongoose to only fetch field "name", "status" but leave all other field

like image 43
ROCK ON Avatar answered Oct 27 '25 00:10

ROCK ON



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!