Ultimate Guide to Using addToSet Operator in MongoDB with Mongoose

AddToSet Operator Featured Image

In this tutorial, I am going to walk you through using the addToSet operator in MongoDB with the help of the Mongoose ODM.

The addToSet operator is a function for an array type of data. It helps us add items or values to an array if they are not present. If in case duplicate data is present while we are adding data to the array, then the duplicate data will not be added.

The addToSet operator in MongoDB works more like the push function in JavaScript. However, the push function doesn’t check for duplicates. It will simply add values to the specified array.

Arrays in JavaScript are of great importance, especially when creating lists. Technically, an array is referred to as a special variable that can store different types of elements or data types in it. It can store strings, numbers, objects, and even arrays.

In this article, I will guide you on using the addToSet operator in MongoDB with the help of the Mongoose ODM. To achieve this, I will create a small Nodejs application to demonstrate with an example. so, let us get started.

How to Use addToSet Operator in MongoDB with Mongoose?

I will create a Nodejs application to be able to demonstrate the usage of the addToSet operator with a clear example. Here are the steps below to get started.

  • Create a Nodejs project directory and change the directory into it:
mkdir nodeaddToSet
cd nodeaddToSet
  • Create your Nodejs project inside the project directory like this:
npm init -y

Once you pass this command, you should see a package.json file created in your project directory. if you wish to change the entry point file name, simply jump to the “main” key in the object, and change its value to the file name you prefer. I will name mine app.js.

  • Next, create the entry point JavaScript file:
touch app.js
  • Let us install all the required NPM packages for our project:
npm i express mongoose
  • Next, let us import all of those packages we installed. As a default behavior, all third-party NPM packages that we install, get stored inside the node_modules directory. Paste this code into the app.js file.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
  • Next, we shall set up a connection with a local MongoDB database. We will use Mongoose for this:
mongoose.connect('mongodb://localhost:27017/farmAndDairyDB', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`YAY! CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`UH OH! MONGO CONNECTION ERROR!`);
        console.log(err);
    })
  • Next, at the end of the app.js file, I will set up localhost port for my app server to listen:
app.listen(8000, () => {
    console.log('Connected to PORT 8000...');
})
  • Next, we will create a new directory named models right in our project directory.
mkdir models
  • Now, create a new file inside the directory named harvests.js, or anything you’d like.
touch models/harvests.js
  • We can now import Mongoose here as well so that we are able to create a schema for our farm and dairy products and the associated model.
const mongoose = require('mongoose');

const productsSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    category: {
        type: String,
        lowercase: true,
        enum: ['fruit', 'vegetable', 'dairy']
    },
});

const Product = mongoose.model('Product', productsSchema);
  • To use the addToSet operator on our documents. I have created and added a few beforehand and this is what they look like:
{ "_id" : ObjectId("6054f4ba0e761c066439114b"), "name" : "Fairy Eggplant", "price" : 1, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114c"), "name" : "Organic Goddess Melon", "price" : 4.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114d"), "name" : "Organic Mini Seedless Watermelon", "price" : 3.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114e"), "name" : "Organic Celery", "price" : 1.5, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114f"), "name" : "Chocolate Whole Milk", "price" : 2.69, "category" : "dairy", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066432875g"), "name" : "Fresh Orange Juice", "price" : 1.52, "category" : "fruit", "__v" : 0 }
  • Let’s say we updated our Mongoose schema after we created and saved these documents. Now, we want to add “juice” in our category key as well. So, for the last document, that is “Fresh Orange Juice”, we want to keep the “fruit” value but also add “juice” value to that array. To do so, we will simply use the addToSet operator like so:
Product.update({
    "$addToSet": { "category": "juice" }
}, function (err, doc) {
    if (err) throw error;
    console.log(`Category updated for: ${doc.name}`);
    console.log(doc);
});

Now, this is what our console prints:

Category updated for Fresh Orange Juice

{
    "_id" : ObjectId("6054f4ba0e761c066432875g"), 
    "name" : "Fresh Orange Juice", 
    "price" : 1.52, 
    "category" : [
        "fruit", 
        "juice"
    ], 

This way we have successfully used the addToSet operator in MongoDB with the help of Mongoose in a Nodejs application.

Read More: Building “Related Post” Engine Using MongoDB Aggregation

Conclusion

Learning to use the addToSet operator in MongoDB with the help of Mongoose ODM.

Noteworthy References

Open Tribute Blog