Open In App

Mongoose SchemaType.prototype.select() API

Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose SchemaType select property is a SchemaType method that allows us to set default select() behavior for a particular path in a mongoose schema. Let’s understand more about this with some examples.

Creating node application And Installing Mongoose:



Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: After creating the ReactJS application, Install the required module using the following command:



npm install mongoose

Project Structure: It will look like the following.

 

Example 1: In this example, we will set the select property of the name path to false, so as not to include this path in the logs of the data from the DB.

Filename: main.js




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
        select: false
    },
    email: {
        type: String
    }
});
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John', email: 'john@test.com' });
const person2 = new Person({ name: 'Doe', email: 'doe@test.com' });
  
(async function () {
    await person1.save();
    await person2.save();
    const persons = await Person.find()
    console.log(persons);
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Example 2: In this example, we will set the select property of the name path to true, but override this setting at the query level to turn it to false, so as not to include this path in the logs of the data from the DB.

Filename: main.js




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
        select: true
    },
    email: {
        type: String,
    }
});
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John', email: 'john@test.com' });
const person2 = new Person({ name: 'Doe', email: 'doe@test.com' });
  
(async function () {
    await person1.save();
    await person2.save();
    const persons = await Person.find().select('-name')
    console.log(persons);
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-select


Article Tags :