Adding information into MongoDb with the help of mongoose

I am currently working with an array of strings and my goal is to iterate through this array and update my collection with its values.

This is the approach I have taken:

 if (employees) {
      employees.map((employee) => {
        Employee.updateOne({ $push: { name: employee.name } })
          .then((data) => {
            console.log(data);
          })
          .catch((e) => {
            console.log(e);
          });
      });
    }

First, I import my model at the top of the file :

const Employee = require('../../models/employees');

The structure of my model is as follows :

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const EmployeeSchema = new Schema({
  name: { type: String },
});

const Employee = mongoose.model('employee', EmployeeSchema);

module.exports = Employee;

Although my console is showing the following output:

{ n: 0, nModified: 0, ok: 1 }

When I check the database, no data is present and no collection is created as expected.

Answer №1

updateOne function in Mongoose has a specific syntax that you should follow.

  1. The first parameter is the condition/filter.
  2. The second parameter is the doc that needs to be updated.
  3. The third parameter is the options, where you must set upsert to true.

Important: With upsert set to true, if the filter doesn't match any documents, updateOne will create a new one.

const insertEmployees = () => {
  try {
    if (employees) {
      employees.map(async employee => {
        let filter = { name: employee.name }
        let doc = { $push: { name: employee.name } }
        let options = { upsert: true }
        await Employee.updateOne(filter, doc, options)
      });
    }
  } catch (error) {
    console.log(error);
  }
}

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

Employ useEffect with numerous dependencies

I am currently working on fetching employee data using the useEffect hook. function AdminEmployees() { const navigate = useNavigate(); const dispatch = useDispatch(); // Fetching employee data const { adminEmployees, loading } = useSelector( ( ...

Developing node.js scripts for configuring an app via the command line interface

file: /config/index.js; var config = { local: { mode: 'local', port: 3000 }, staging: { mode: 'staging', port: 4000 }, production: { mode: 'production', port ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

Exploring the world of Node.js callback parameter passing

Currently, I am diving into the world of Node callbacks and JavaScript in general. As I delve deeper, I find myself puzzled by the following snippet: var request = require('request'); request('http://www.google.com', function (error, ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined" The customers constant is defined above, so I'm unsure where the undefined value is origin ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

Guide on dynamically updating a div in PHP with a mix of text output and images at regular intervals

My current project involves creating a browser-based card game primarily using PHP, with potentially incorporating other languages to help me enhance and test my PHP skills. However, I've encountered difficulties while attempting to implement various ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Redirecting clients on form submission from the client side

In my cshtml page, I have a script that calls a controller method via jQuery on form submission. It passes data to the method using the values from a datePicker control. Here's an example of the script: $('form').submit(function () { v ...

JavaScript code that uses jQuery does not function properly on an HTML form

Hello everyone, I am having trouble with some JavaScript code. Here is what I have: $(document).ready(function(){ $(".replyLink").click(function(){ $("#form-to-"+this.id).html(htmlForm()).toggle(500); return false; }); function htmlForm(){ var htm ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must ...

Tips for updating state and rendering in a function component in React Native:

I am attempting to update the state before rendering the component in a function component. While I have found suggestions to use the useEffect hook for this purpose, I am finding the information on the React official site somewhat perplexing. The docume ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code: $scope.redirect = function () { const params = $httpParamSerializer({ initval: { user: { id: 1, ...

What is the optimal method for saving and organizing data in SQL?

I currently have a MySQL table containing data that is displayed in an HTML table. Using JavaScript and drag & drop functionality, I am able to locally sort this table. My question is, what is the most effective method for saving these sorting changes? W ...