Updating a MongoDB collection by replacing its values with those from an array

Looking to update all documents in a MongoDB collection with values from an array.

Let's consider the following schema for the documents in MongoDB:

{
 "key":"value",
 "key2":"value2"
}

We have an array: ["test", "test2"]

The goal is to iterate through the array so that the "keyN" key in all documents in the collection gets updated with either "test" or "test2"

{
  "key":"value",
  "key2":"value2",
  "keyN":"test"
}
{
  "key":"value",
  "key2":"value2",
  "keyN":"test2"
}
{
  "key":"value",
  "key2":"value2",
  "keyN":"test"
}

What would be the best approach to achieve this? I attempted to use forEach, but struggled to create the iterator on the array.

Answer №1

Uncertain if this meets your requirements...here is a sample of test using mongoose schema, not the actual mongodb document.

Please confirm if this answer is accurate or suggest any enhancements needed for the test/code.

https://i.sstatic.net/9XQJ8.png

Mocha Test File

var expect = require('chai').expect,
mongooseMock = require('mongoose-mock'),
proxyquire = require('proxyquire'),
sinon = require('sinon'), 
chai = require('chai'),
sinonChai = require("sinon-chai");
chai.use(sinonChai);

var AIterator;
describe('model', function() {
    beforeEach(function (done) {
        AIterator = proxyquire('./ArrayIterator', {'mongoose': mongooseMock});
        done();   
    });
    
    it("should iterate the array",function(done){
        setTimeout(done, 15000);
        var callback = sinon.spy();
        var aIterator=[];
        aIterator[0] = AIterator.create({"key":"value1","key2":"value2","keyN":"value3"}, callback);
        aIterator[1] = AIterator.create({"key":"value4","key2":"value5","keyN":"value6"}, callback);
        aIterator[2] = AIterator.create({"key":"value7","key2":"value8","keyN":"value9"}, callback);
        var x=0;
        
        aIterator.forEach(function(element) {
            if (element.keyN=="value9") {
                element.keyN = "test";        
            }                 
         }, this);
         
        expect(aIterator[2].keyN).equals("value3");
        done(); 
    });
});

Code File

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var arraySchema = new Schema({
    key: String,
    key2: String,
    keyN: String
});

var NewArray = new mongoose.Schema(arraySchema);
NewArray.statics.create = function(params, callback) {
    var newUpdate = new NewArray(params);
    newUpdate.save(function(err, result) {
        callback(err, result);
    });
    return newUpdate;
};
var ArrayIterator = mongoose.model('Model', NewArray);
module.exports = ArrayIterator;

Alternatively,

another test to handle values in the input array, if that aligns with your intention:

it("should iterate the array",function(done){
        setTimeout(done, 15000);
        var callback = sinon.spy();
        var testArray = ["test", "test1"];
        var aIterator = [];
        aIterator[0] = AIterator.create({"key": "value1", "key2": "value2", "keyN": "value3"}, callback);
        aIterator[1] = AIterator.create({"key": "value4", "key2": "value5", "keyN": "value6"}, callback);
        aIterator[2] = AIterator.create({"key": "value7", "key2": "value8", "keyN": "value9"}, callback);
        var x = 0;
        
        testArray.forEach(function(element) {
            if (element == "test") {
                aIterator.forEach(function(element1) {
                    if (element1.keyN == "value9") {
                        element1.keyN = element;        
                    }                 
                }, this);
            }
        }, this);
        
        expect(aIterator[2].keyN).equals("value3");
        done(); 
});

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

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

php code for verifying the format of MongoDB ids

How can I validate a MongoDB ID from a query string? I want to redirect to another URL if the MongoDB ID is not valid. Here's how to get the query string: if(count($_GET)>0 && $_GET['uid']){ // Get the ID from the query string $qu ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

Changing the time zone of a browser using JavaScript or jQuery

After researching numerous discussions on the topic, it appears that changing the browser's timezone programmatically is not possible. Although the moment-timezone.js library allows us to set timezone for its objects, it does not affect the browser&ap ...

Execute function asynchronously after useEffect has completed

I'm curious about how to run a function following the use of useEffect to fetch data, where the function manipulates the retrieved data. import React, { useState, useEffect } from 'react'; const Result = (props) => { const [ playerN ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

Having trouble displaying the Chrome context menu for a specific Chrome extension

I've read through several posts on this topic, but I'm still struggling to identify the issue with my implementation of the Chrome contextMenu API. I simply copied the code from a tutorial on Chrome APIs, and though there are no errors, the menu ...

"Exploring the dynamic features of jQuery's mobile listview and

As I work on creating a mobile app using jQuery Mobile, I find myself facing some challenges. Despite my efforts and attempts at different methods, I have not been successful in achieving the desired functionality. Specifically, I am trying to implement a ...

The first div should be hidden when the toggle is activated

I am currently working on a CRUD project and incorporating some Javascript/JQuery into it. I have a button labeled "Add", which, when clicked, displays a specific div element. However, I'm facing an issue where the div is already visible before the us ...

Loading arrays into a Joomla JTable and making field edits

After experimenting with using an array in JTable's load function, I attempted the code below: public function delete($id = null) { $app = JFactory::getApplication(); $id = $id ? $id : $app->input->get('files', array(), ' ...

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

Encountering the "Cannot set headers after they are sent" error; it should be noted that render()/json() has only been called

I am encountering an issue while trying to send a response back to the client after inserting data into the database. Although I haven't called response.json() or response.render() twice in my code, I keep receiving the error message: Error: Can&apos ...

I have some questions regarding the process of adding documents to MongoDB using the native driver in Node

Encountering challenges when working with write concerns in the mongodb native driver for Node.js. Utilizing a single MongoDB server on localhost. Below is the code snippet being used: function insertNewDoc(newdoc, cbsuccess, cberror){ db.collection(&apo ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...

Converting Fancy Text to Plain Text using Javascript: A Step-by-Step Guide

I am currently developing a search feature in JavaScript that supports both regular and fancy text styles. However, I have encountered an issue with the search functionality not working when searching for: Fancy text value: ...

Discovering the stable order indices of the top n elements within an array

I am working with a number and an array: n = 4 a = [0, 1, 2, 3, 3, 4] My goal is to identify the indices that correspond to the top n elements in array a, but I want them in reverse based on their size. In case of equal element sizes, I prefer a stable o ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

react-hook-form's useFieldArray function does not display data from an API when values are passed in

Utilizing a fieldArray, I am constructing a form with react-hook-form. This form serves the dual purpose of creating and updating a user, and makes use of the "values" prop from react-hook-form. The field within the fieldArray API consists of two basic tim ...