Chris Rutherford
Chris Rutherford

Reputation: 1672

Mongoose Model.find().select() If Select is an empty string What's returned?

Let's assume that we're using a simple schema of this:

const phoneRegex = require('./phoneRegex');
const Schema = require('mongoose').Schema;
const PersonSchema = new Schema({
  firstName: String,
  lastName: String,
  phone: {
    type: String,
    regex: phoneRegex,
  },
  Address: {
    street1: String,
    street2: String,
    city: String,
    state: String,
    zip: String,
  }
});

module.exports = Person = require('mongoose').model('Person', PersonSchema);

and I want to have a preset call to mongoose to find a list of people, but I want to have the option to limit what's returned from the database. I understand I can use the select() function of the model, but what happens when you provide an empty string? (i.e. Person.find(options).select('');)

My predefined function looks like this:

//sample options object.
const options = {
  firstName: {
    $regex: '^John',
    $options: 'i',
  },
};
const Person = require('./person');
const fetchAll = (Options, select = '') => {
  return Person.find(Options).select(select);
};

I understand that I would want to pass the property name to select it for return, but is an empty selection string the same as "SELECT NONE"?

Upvotes: 2

Views: 2147

Answers (2)

KDM
KDM

Reputation: 13

After testing

someDb.find().select("")

returns documents with all the fields selected (except the ones with select: false in the schema)

Upvotes: 0

Plancke
Plancke

Reputation: 1139

After reading through the docs it looks like that all fields will be ignored except for the _id field since that's included by default. You're saying include nothing, exclude everything else.

I don't currently have a mongoose setup to test this, so it's more of an educated guess.

Upvotes: 2

Related Questions