How to insert into an array in MongoDB using Mongoose?

I have an issue with my model where I am attempting to push an array to an empty array, but for some reason the changes are not reflected in Compass.

Various approaches were tried to remedy this situation such as setting the type of user_list property to array and initializing it as an empty array using []. Additionally, deleting and recreating the entire database was done to rule out any memory-related problems.

Model:

const guildSchema = new Schema({
    guild_name: String,
    guild_id: { type: String, unique: true },
    ...
    user_list: []
})

Fetching the array and attempting to push:

bot.on("guildUpdate", (oldGuild, newGuild) => {
    let userList = newGuild.fetchMembers().then(function(results){ console.log(results.members.keyArray()); userList = results.members.keyArray();
        Guild.findOneAndUpdate({guild_id: oldGuild.id}, {"$set": {"guild_name": newGuild.name, "guild_icon": newGuild.iconURL}}, {"$push": {"user_list": userList}}, function(err) {
            if (err) throw (err);
        });
    }).catch(console.error)
})

console.log(results.members.keyArray())
displays the desired array without any issues. Furthermore, updates made using $set are visible in Compass. However, the problem lies specifically in pushing to user_list, as Compass fails to reflect these changes and continues to display a blank array post-update.

Answer №1

Issues are arising because the $push operator was mistakenly placed as a 3rd argument in the update query, when it should actually be included in the 2nd argument with $set. The 3rd argument is intended for update query options such as new and upsert.

Here is the revised code snippet:

Guild
    .findOneAndUpdate({
        guild_id: oldGuild.id
    }, {
        "$set": {"guild_name": newGuild.name, "guild_icon": newGuild.iconURL},
        "$push": {"user_list": userList} // This line should be part of the second argument
    }, function(err) {
        if (err) throw err;
    });

Additionally, ensure that you have defined your array in the schema along with its type.

const guildSchema = new Schema({
    guild_name: String,
    guild_id: { type: String, unique: true },
    ...
    user_list: [String]//if type is String
})

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

How can you remove the add button in React Material Table?

Within the material table, there is a feature that allows for the conditional hiding/disabling of action buttons. Is there a way to do the same for the Add button located at the top of the table? See screenshot below ...

The drop-down menu is failing to display the correct values in the second drop-down

Having trouble with the update feature in this code. There are 2 textboxes and 2 dropdowns, but when selecting a course code, the corresponding values for the subject are not being posted. Can anyone assist? view:subject_detail_view <script type="te ...

Prevent users from selecting dates in the future using the Bootstrap datepicker

One issue I am facing is how to prevent users from selecting future dates in a form with date input. Here's the solution I came up with: $(document).ready(function(){ $('.month').datepicker({ format: 'yyyy-mm-dd', ...

Tips for retrieving the content of an input field using Angular

function HomeController($scope, navbarService) { var vm = this; $scope.showHeader = true; $scope.userNameNav =''; $scope.$on('toggleHeader', function(event, data) { $scope.showHeader = data; }); $s ...

What is the proper way to utilize $location within a standard function?

I am working on an Angular app that consists of both AngularJS and plain JavaScript such as Ajax. I am trying to figure out how to use $location within a function without passing it as a parameter. function x() { $location.path('/error').repl ...

Dynamic Positioning in Javascript Application

When working on a javascript project, I needed to create a div element. Here is the code snippet I used: const divStyle = {left: offsetPercent + '%', 'position': 'absolute'}; <div style={divStyle}/> However, I encounte ...

Capturing user-selected option from dropdown menu using npm

I am a beginner when it comes to node.js and async programming. My current project involves creating a program that shuffles a Spotify playlist. I have managed to store the user's playlists in an array for easier access. My goal is to present this ar ...

Perform a POST request in JavaScript and handle the response in PHP

Currently, I am in the process of gathering data through a form and executing this JavaScript: fetch('process.php', { method: 'POST', body: formData, }).then(response => alert( response ) ); The execution of process.php hap ...

What can I do to prevent object.style.backgroundColor in my JavaScript file from overriding my class:hover effect in my CSS file?

I am looking to enhance my user experience by allowing them to either hover over an option to highlight it or press a number key to highlight the corresponding option. However, I am facing an issue where the object.style.backgroundColor function overrides ...

How can I use jQuery to pinpoint where my focus currently lies and debug any issues?

Triggering focus() on an element is a simple task, but after encountering debugging problems, I've come to realize that finding out where my focus has shifted can be quite challenging. The issue arises when I'm creating a modal window using jq.UI ...

Sequelize hooks fail to trigger when manually updating records

As a newbie to sequelize and RDBMS, I recently incorporated a sequelize hook in the following manner bills.afterBulkUpdate((instance, options) => { console.log(instance); }); I am curious if updating any record in the bills table manually (via DB sc ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

Why does the address bar show value changes in IE when using window.location.hash, but the value doesn't change in the DOM when going

Here is a sample JavaScript code that attempts to detect the back button event: document.location.hash="#1"; document.location.hash="#2"; document.location.hash="#3"; function check() { if("#3"!=window.location.hash) { alert("Back button clic ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

Utilizing jQuery to Determine Character Count

I've tried everything on the site, but nothing seems to be working. I'm attempting to create a function that triggers when the character count in a div exceeds a certain number, but it's not functioning as expected. Any assistance would be g ...

Issue: Unable to set headers after they have been sent while using express-fileupload in the application

app.post('/profile', function(req, res) { // save file if (req.files) { let sampleFile = req.files.sampleFile; sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) { if (err) ...

Building a reusable Button component in React using TypeScript that handles not assignable type errors

Attempting to create a reusable component in reactjs using typescript is currently resulting in the following error: Type '{ children: string; type: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButt ...

Gather information based on specific dates and store it in an array

I am trying to calculate the number of individual jobs from various rows. The relevant columns for this are "created_at" and "data," which is a JSON Array containing all the single jobs that need to be counted. My goal is to tally the total number of job ...

Transforming all numbers to a consistent scale with the help of Numeral JS

Is there a way to customize the output of the numeral.js function so that it always returns numbers in thousands? For example, converting 1000000 to 1000k and 100 to 0.1k. console.log( numeral(1000000).format('0a') ); <script src="https ...