How to Select Specific Fields in Node JS and Mongoose

Hey there! If you're like me, diving into the exciting world of Node.js and Mongoose, you might wonder how to pick out specific pieces of data from your MongoDB database. Well, fear not! I'm here to guide you through the process step by step.

In this article, we'll see how to exclude fields when we are retrieving data from how to exclude fields in the MongoDB database. you can select specific fields from the database or exclude certain fields in the MongoDB database with Node JS and Mongoose.

Also, you can get specific columns in Node JS REST API. In REST API you can easily select specific fields.

When using string syntax, prefixing a path  - will flag that path as excluded. When a path does not have a - prefix, it is included.

So, let's see how to select specific fields in Node JS and Mongoose, how to exclude fields in Mongoose, Mongoose find select, and Mongoose select multiple fields and Node JS.MongoDB selects exclude fields.

Step 1: Setting Up Your Node.js Project

First things first, make sure you have Node.js installed on your system. You can download and install it from the official Node.js website if you haven't already.

Once Node.js is set up, create a new directory for your project and navigate into it using your terminal or command prompt.

Now, let's initialize a new Node.js project by running the following command:

npm init -y

This command will create a package.json file with default values.


Step 2: Installing Mongoose

Mongoose is an elegant MongoDB object modeling tool designed to work in an asynchronous environment. To install Mongoose, run the following command in your terminal:

npm install mongoose


Step 3: Connecting to MongoDB

Before we can start selecting specific fields, we need to connect our Node.js application to MongoDB using Mongoose. Create a new file called db.js in your project directory and add the following code:

const mongoose = require('mongoose');

.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Failed to connect to MongoDB', err));

Make sure to replace 'mongodb://localhost:27017/mydatabase' with the connection URL of your MongoDB database.


Step 4: Creating a Mongoose Schema

Now, let's define a Mongoose schema for the documents in our MongoDB collection. Create a new file called products.js in your project directory and add the following code


const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Name must be required"]
    price: {
        type: Number,
        required: [true, "Price must be required"]
    featured: {
        type: Boolean,
        default: false
    rating: {
        type: Number,
        default: 4.5
    createdAt: {
        type: Date,
    company: {
        type: String,
        enum: {
            values: ['Apple', 'Samsung', 'Dell', 'HP'],

module.exports = mongoose.model("Product", productSchema);


Step 5: Selecting Specific Fields

To select specific fields from your MongoDB documents, you can use the select() method provided by Mongoose. When you are working on REST API this example is used.

const Product = require("../models/products");

const getAllProducts = async (req, res) => {
    const { company, name, featured, sort, select } = req.query;
    const queryObject = {};

    if (company) { = company;

    if (name) { = {
            $regex: name, $options: "i"

        queryObject.featured = featured;

    let apiData = Product.find(queryObject);

        let sortFix = sort.split(",").join(" ");
        apiData = apiData.sort(sortFix);        

        let selectFix = select.split(",").join(" ");
        apiData =;        

    const products = await apiData;
    res.status(200).json({ products })

module.exports = getAllProducts;



API Response 

"products": [
        "_id": "65dc301f352a919d18074cb7",
        "name": "Iphone14",
        "price": 170,
        "company": "Apple"
        "_id": "65dc301f352a919d18074cb8",
        "name": "N4030",
        "price": 200,
        "company": "Dell"


const User = require('./model');

User.find({}, 'username email', (err, users) => {
  if (err) {


// include a and b, exclude other fields'a b');
// Equivalent syntaxes:['a', 'b']);{ a: 1, b: 1 });

// exclude c and d, include other fields'-c -d');

// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
  foo: { type: String, select: false },
  bar: String
// ...'+foo'); // Override foo's `select: false` without excluding `bar`

// or you may use object notation, useful when
// you have keys already prefixed with a "-"{ a: 1, b: 1 });{ c: 0, d: 0 });

Additional calls to select can override the previous selection:{ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }{ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 0 }


Step 6: Conclusion

And there you have it! You've successfully learned how to select specific fields from MongoDB documents in Node.js using Mongoose.

That's it for now! If you have any questions, feel free to ask. Happy coding!


You might also like:


Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.