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');

mongoose.connect('mongodb://localhost:27017/mydatabase')
.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

models/products.js

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,
        default: Date.now()
    },
    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) {
        queryObject.company = company;
    }

    if (name) {
        queryObject.name = {
            $regex: name, $options: "i"
        };
    }

    if(featured){
        queryObject.featured = featured;
    }

    let apiData = Product.find(queryObject);

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

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

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

module.exports = getAllProducts;

Output:

http://localhost:5000/api/products?select=name,company,price

API Response 

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

Example:

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

User.find({}, 'username email', (err, users) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(users);
});

Example:

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

// exclude c and d, include other fields
query.select('-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
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`

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

Additional calls to select can override the previous selection:
query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }
query.select({ 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

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. 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.

RECOMMENDED POSTS

FEATURE POSTS