Changing values in object using Mongoose in MongoDB

Currently, I have a basic collection stored in MongoDB using Mongoose.

My users model consists of a single field of type object, and I am looking to dynamically modify this object. However, despite my attempts using findByIdAndUpdate(), findById, findOne(), and findOneAndUpdate(), the code does not seem to be working as expected.

const UsersSchema = mongoose.Schema({
        likes: {}
    },
    { collection: 'users' });

const Users = mongoose.model('Users', UsersSchema);
const id ="5b4c540f14f353a4b9875af4";
const themes = ['foo', 'bar'];

Users.findById(id, (err, res) => {

    themes.map(item => {
        if (res.likes[item]) {
            res.likes[item] = res.likes[item] + 1;
        } else {
            res.likes[item] = 1;
        }
    });

    res.save();
});

Answer №1

In order to resolve this issue, I suggest expanding the fields in your schema:

Below is an example using this data:

const UsersSchema = new mongoose.Schema({
  likes :[
    {
      thema:{
        type: String
      },
      likes_amount:{
        type: Number
      },
      _id:false
    }]
});

module.exports = mongoose.model('Users', UsersSchema);

An additional user has been included:

   var newUser = new UserModel({
      likes:[{
        thema:'foo',
        likes_amount:1
       }]
   });
   newUser.save();

https://i.sstatic.net/o0PMJ.png

Here is the code that increments the number of likes per theme:

 const themes = ['foo', 'bar'];
  const userId = "5b4d0b1a1ce6ac3153850b6a";

  UserModel.findOne({_id:userId})
    .then((result) => {

      var userThemes = result.likes.map(item => {
        return item.thema;
      });

      for (var i = 0; i < themes.length; i++) {
        //if it exists, increment by 1 like
        if (userThemes.includes(themes[i])) {
          UserModel.update({_id: result._id, "likes.thema" : themes[i]}, {$inc: {"likes.$.likes_amount": 1}})
            .then((result) => {
              console.log(result);
            }).catch((err) => {
              console.log(err)
            });
        } else {
         //if it doesn't exist, create a theme with 1 like
          UserModel.update({_id: result._id},
            {
              $addToSet: {
                likes: {
                  $each: [{thema: themes[i], likes_amount: 1}]
                }
              }})
            .then((result) => {
              console.log(result);
            }).catch((err) => {
              console.log(err)
            });
        }
      }
    }).catch((err) => {
     console.log(err)
    });

Database outcome after increment:

https://i.sstatic.net/rZar9.png

I hope this explanation is helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it important to avoid reassigning parameters in real-life situations? Can you provide an example of a problem that may arise from this practice?

Many inquiries focus on the best methods to follow the no-param-reassign linting rule, but there is a lack of requests to demonstrate the reasoning behind the rule. It is common to hear claims like 'Assigning values to variables defined as function p ...

Having trouble with Angular's ng-class performance when dealing with a large number of elements in the

I've encountered a performance issue while working on a complex angular page. To demonstrate the problem, I've created a fiddle that can be viewed here. The main cause of the performance problem lies in the ng-class statement which includes a fu ...

Combining properties of JavaScript objects into one

Just starting my Vue journey and encountering a slight challenge. Displayed below is a table with various items: Whenever an item is selected and its quantity increased, I need my addOptional method (optional) to update a variable with the item's qu ...

Waveform rendering in HTML5 using wavesurfer.js struggles to handle large mp3 files

Recently, I was considering incorporating wavesurfer.js into one of my projects so I decided to explore the demo on To test it out, I uploaded a large mp3 file (approximately 2 hours long) onto the designated area in the middle of the page. It appeared to ...

What could be causing the .hover function to malfunction and how can I make it so that the .hover function only applies within the corner radius area?

I am attempting to make circles react to my jquery .hover function. Below is the JavaScript code I am using: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + ...

Caution: A duplicate key was found in ReactJS when attempting to flatten children

Currently, I am utilizing Tabs from Material UI to showcase a List component that is filtered by the tab. Take a look at the code snippet below from my Container Component: <Tabs className="DrawerTabs" ...

Methods to declare the data type of a field when inserting in MongoDB

After thoroughly reviewing the Mongo documentation, I am struggling to locate instructions on how to define a type during insertion. I have a feeling that it is a small detail that I may be overlooking. ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

JavaScript | Determining the coordinates of where on the image X and Y were clicked

My goal is to determine the position of an x and y location when a user clicks on an image. This information will be used to add a spot to the image that displays relevant information. The content for the spot will be dynamically loaded from a SQL database ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

What is the most effective way to divide input elements into an array in Angular?

How can I bind an input value to an ng-model as an array? For example, if I enter one, two, three, I want the resulting model to be [ "one","two","three" ]. Currently, this is my approach: <input type="text" ng-model="string" ng-change="convertToArra ...

The file always fails the Regex test in Node.js

I am dealing with a log file that contains lines structured like this: [Thu Mar 30 2017 11:24:51 GMT+0100 (WEST)] {"serial":"CA-2M-1107619","type":"iface","body":{"action":"up","device":"tun_man","ip":"127.255.0.10","ip6":"2016:900d:c0de::1001"} My goal ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

Error encountered when initializing NextJS Firebase Authentication App

I'm encountering challenges with implementing Firebase authentication using Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection to Firebase. However, I'm running into an issue whe ...

What is the process for sending a data response with express?

Seeking guidance on running the .get operation on a JSON file I have stored at the path /scripts/src/data/*.json. When making the request, I am setting the headers but unsure how to retrieve the resulting data or where to view this request. Any assistance ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

Exploring the chosen choice in the Material Design Lite select box

Consider the following scenario. If I want to extract the name of the country chosen using JavaScript, how can this be achieved? <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select getmdl-select__fullwidth"> ...

Inserting the factory._id into the user collection is not achievable with node.js and MongoDB

In the process of developing a flutter application, I am working on a feature where users can add phone numbers to invite them into the database. Each phone number added should also be assigned a factory ID. For instance, when a user clicks the add button ...