Problem with inserting data into MongoDB

I am facing a challenge with my Mongo DB structure, which is structured as follows:

db.users.find().pretty();
{
    "_id" : ObjectId("52b42b148ffa91f7ebbe8ebc"),
    "username" : "test",
    "password" : "test",
    "party" : [
        "4988",
        "5037"
    ],
    "something" : [
        "3571"
    ],
    "ludilo" : [],


}

In my application built on express js, I use this module to connect to Mongo https://npmjs.org/package/mongodb.

My question is how can I add a new entry into the "something" array for a user based on the session id.

I attempted the following code snippet, but unfortunately it did not work as expected

var collection = db.collection('users');
         collection.find({'_id':new ObjectID(req.user.id)}).toArray(function(err, items) {
            console.dir(items);
          }).insert({"something":"1234"});

Answer №1

To add a new value to an array, you can use the $push method like this:

db.users.update(
    { _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
    { $push: { something: "1234" } }
)

If you want to avoid duplicates in your array, you can utilize the $addToSet command instead:

db.users.update(
    { _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
    { $addToSet: { something: "1234" } }
)

Answer №2

Here's a snippet of code you can test out:

collection.find({_id: new ObjectID(req.user.id)}).toArray(function(err, items) {
  var doc = items[0];
  doc.something.push('1234');
  collection.update({_id: doc._id}, {$set: {something: doc.something}}, {safe: true}, function() {
    //carry out your next steps
  });
});

I've tested this code locally and it seems to be functioning properly.

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

What are the endless possibilities of JavaScript?

My main goal is to maximize client-side functionality using JavaScript. Specifically, I want to create an interface that displays information to users and processes their responses using JavaScript. I plan to use a web server only for retrieving a data fil ...

Floating navigation bar that appears and disappears as you scroll

My webpage has a dynamic navbar that consists of two parts: navbarTop and navbarBottom. The navbarTop should appear when the user has scrolled down more than 110 pixels, while the navbarBottom should show up when the user scrolls up. The issue I am facing ...

Utilizing JavaScript and Flexbox to generate a 16x16 grid within a div element

I am facing an issue with stretching my grids horizontally in order to fit perfectly within my container. The objective is to create a 16/16 grid using flexbox and dynamically generate divs in JavaScript, which will then be placed into a container (sketch- ...

What is the best way to input data into the verified full name box?

.html file executed code <input type="name" [(model)]="x.name" class="form-control" pattern="[a-z]" > Greetings to the members of Stack, I am in need of assistance. I am relatively new to Angular and I am looking for a way to validate the full nam ...

Perform a toggle action on the first row when clicking within the current row using Jquery

I've been grappling with the idea of creating a function that can display and hide a comment field when a button is clicked. The challenge here is that there are multiple line items with their own comment boxes. I want to find a way to achieve this wi ...

Activate a JQuery anchor's onclick function without redirecting the browser to the specified href

I am looking to create an a tag with both an href and an onclick function. However, I want the browser to only execute the onclick function when the user clicks the link, without navigating to the href. I attempted the following solution: function testF ...

Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string. Suppose I have two checkboxes labeled: label1 and label2, my a ...

Toggle button visibility on ng-repeat item click

Hello everyone, I'm encountering an issue with displaying and hiding buttons in ng-repeat. <div class="row" ng-repeat="item in items"> <button type="button" ng-click="add()">+</button> <button type="button" ng-click="remo ...

Displaying the Laravel modal again with the identical data upon encountering a validation error

I have a table displaying data from a database where each row contains a button that opens a modal with the current clicked row id. Here is an example of the code: <tbody> @foreach($receivedShipments as $shipment) <tr> ...

How can I prevent webpack from showing the default output after a module build error occurs?

Having difficulty figuring out how to prevent webpack from displaying an error message like the following when encountering a SyntaxError. throw new Error("Module build failed: SyntaxError: ...) Ideally, I'd prefer it not to show any output at all i ...

Utilizing a promise array in conjunction with v-data-table

In my custom table component, I am using a v-data-table to display data that is passed as a prop. I perform some data cleaning operations and then call an asynchronous function to fetch additional data from an API: //load cloud storage data const cleanData ...

MongoDB failing to populate data for NodeJS server request

I have developed an application that sends POST request data to a NodeJS server in JSON format. The content is structured as follows: {"encrypteddata": "someencryptedvalueofthetext"}. This information is stored in a MongoDB database. I have created two f ...

Formik introduces a fresh Collection of values rather than just appending a single value

Currently, I am working on a form that utilizes cards for user selection. The form is built using the useFormik hook along with yup for validation purposes. Below is an example of the code structure: In the file form.tsx, we have: export const validationS ...

What is the process by which open edx stores course content data in a mongo database?

Currently, I am developing an e-learning platform that resembles open edx. All the course materials are saved in a mongo database and now I need to determine the disk space usage for each course. The database name is edxapp, which includes the following ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

The functionality of the mathjs eval function varies when used with and without a string input

When I calculate Arithmetic operations using the math.eval function without quotes, null values are ignored and correct results are obtained. However, if I use quotes in the same function, it throws an error. The issue is that I require strings because I ...

What is the best way to set the `value` attribute and `v-model` attribute for a custom Vue component?

I am seeking to develop a unique Vue component that functions as a "radio div" - essentially, a div with the ability to act like a radio button where only one among multiple can be selected at a time. The div will also have a slot for including any desired ...

Effective methods for synchronizing two dropdown menus with varied displays using React

Having a list of countries with specific key-value pairs, I am interested in creating two Dropdown lists. The first will display the keys, while the second will show the corresponding text values. The main objective is to provide the option to select eith ...

Using arrays in Sequelize and Express.js is a common task when working with databases in web

What is the best way to create a sequelize model using sql dialect that involves arrays and how can one perform push/pop operations on it? I would greatly appreciate any code snippets that you can provide. ...