Guide on adding information to an array field in MongoDB with Node.js

I want to update the articles attribute by adding the titles of different articles. The function in my user.controller.js file looks like this:

module.exports.savearticle = (req, res, next) => {
  User.findOneAndUpdate(
    req._id,
    {
      $addToSet: { articles: req.body.articles }
    },
    {
      new: true
    },
    function(err, savedArticle) {
      if (err) {
        res.send("Error saving article");
      } else {
        res.json(savedArticle);
      }
    }
  );
};

I have a separate router page, index.router.js, where all my routers are defined, including the route for this function:

router.post("/savearticle", ctrlUser.savearticle);

I am testing the function using Postman. I set a key to articles and the value to article1 in form-data. However, the response I get is:

{
    "articles": [
        null
    ]
}
Why is it returning null? When I use console.log(req.body.articles), it shows undefined. Why is that happening instead of showing article1?

This is the schema I'm creating in my user.model.js page:

var userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    required: "Full name cannot be empty"
  },
  email: {
    type: String,
    required: "Email cannot be empty",
    unique: true
  },
  password: {
    type: String,
    required: "Password cannot be empty",
    minlength: [4, "Password must be at least 6 characters"]
  },
  saltSecret: String,
  articles: Array
});

And here is the user registration function in the user.controller.js file:

module.exports.register = (req, res, next) => {
  var user = new User();
  user.fullName = req.body.fullName;
  user.email = req.body.email;
  user.password = req.body.password;
  user.articles = [];
  user.save((err, doc) => {
    if (!err) {
      res.send(doc);
    } else {
      if (err.code == 11000) {
        res.status(422).send(["Duplicate email address found."]);
      } else return next(err);
    }
  });
};

Answer №1

It seems that you are encountering an issue with the findOneAndUpdate method due to incorrect parameters being passed. Make sure to check the type of req._id (you can do this by setting a breakpoint or using console.log(req._id)). If it is a string, you will need to convert it to a mongoose.mongo.ObjectId.

module.exports.savearticle = (req, res, next) => {
  let userId = req._id;
  if((typeof userId) === 'string'){
     userId = mongoose.mongo.ObjectId(userId);
  }
  User.findOneAndUpdate(
    {_id : userId},
    {
      $push: {articles: {$each : req.body.articles } } //$each need if  req.body.articles is an array, else use  $push: {articles: req.body.articles } instead of
    },
    {new: true},
    function(err, savedArticle) {
      if (err) {
        res.send("Error saving article");
      } else {
        res.json(savedArticle);
      }
    }
  );
};

Answer №2

Consider the following steps:

  1. Convert your req._id to an Object Id

req._id = mongoose.Types.ObjectId(req._id);

  1. When using Postman, ensure you send data in body as raw type and select JSON from the dropdown menu. https://i.stack.imgur.com/2PrI4.png

Remember: To have only unique values in the array "articles", use #addToSet; otherwise, use $push.

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

Role reactions in Discord.js are a useful feature that allows users

Whenever this code is executed, an error message is displayed. The bot has full administrative privileges over the server where I am testing it. client.on('messageReactionAdd', async (reaction, user) => { if (reaction.message.partial); awa ...

Confusion in Discord.js API Integration (G4F)

Seeking assistance with creating a discord chatbot using discord.js and g4f library. My background is mostly in python, so I'm not very familiar with node.js. Although I managed to get the login functionality working, the bot is not sending messages a ...

Utilizing Node.js and Sequelize to add data into a database

For my project, I am utilizing MySQL database and Sequelize Js to manage data. Currently, I have two models set up: Post code model: module.exports = function(sequelize, Sequelize) { var Post_code = sequelize.define('post_code', { id: { ...

Why is the updated index.html not loading with the root request?

I'm currently working on an Angular app and facing an issue with the index.html file not being updated when changes are made. I have noticed that even after modifying the index.html file, requests to localhost:8000 do not reflect the updates. This pro ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Capturing website links with Node.js asynchronously

My code snippet is as follows: const fs = require('fs'); const screenshot = require('screenshot-stream'); const urlp = require('url'); var urls=[ 'https://archive.org/details/8bitrecs', 'http://hackaday.com/&ap ...

An issue has been identified where linked files are not being loaded properly when utilizing the sendFile method in Node.js and Express.J

When using Express.js 4, I encountered an issue where the browser does not load additional assets such as javascript files or images when serving a page with the sendFile method. Accessing the page through a URL works fine, but the problem arises when load ...

What is the process for creating custom command settings for each specific Discord server or guild?

If the server admin writes "!setprefix $" the bot will change its prefix from "!" to "$", but this change will only apply to that specific server. ...

broadcast a video file from a Node.js server to multiple HTML5 clients at the same time

After researching online, I have been looking for a way to simultaneously stream a video.mp4 to multiple html5 clients. Despite reading various tutorials, I haven't found the ideal solution using nodejs. Do you have any suggestions or alternative met ...

Executing a custom node module in script commands specified in package.json file

I created a node package called my-module which functions properly. When I add this module to a larger project, I would like it to be executed through the packege.json file. Here is how it currently works: "scripts": { "myModule" : "node ./node_modul ...

The NodeJS gRPC client is experiencing an UNAVAILABLE status and is not attempting to retry

I've got a NodeJs client that connects to a GRPC backend through an AWS Load Balancer. The client is set up as a singleton, but we're running into issues where the connection becomes UNAVAILABLE after a while, leading to TCP Socket write errors d ...

Tips for closing process.stdin.on and then reopening it later

I've been facing a challenge with an exercise. In this exercise, the client will input a specific integer x, followed by x other y values separated by spaces. The output should be the sum of each y value, also separated by spaces. For example: Input: ...

Leveraging the Request npm package synchronously within Meteor 1.3

In my Meteor 1.3.2.4 project, I tried utilizing the synchronous features of the request npm package. I initially followed the instructions provided in this guide article from Meteor and attempted to use Meteor.bindEnvironment. Here's the code: impor ...

What would occur in the event that NPM were to shut down completely?

I can't help but wonder, what would the repercussions be if NPM were to unexpectedly cease operations? With so many NodeJS projects dependent on its packages, would they all be left in a lurch? Is there even a possible recovery plan for such a scenari ...

Error: The call stack has reached its maximum size while running an npm install

Attempting to execute npm install, encountered the following console output: npm ERR! Linux 4.8.0-27-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! Maximum call stack size exceeded npm ...

What are some methods to display search outcomes in mongodb?

I have created a Comment Model with specific fields including userId, contentId, repliedTo, and text. The schema for the Comment Model is defined as follows: const CommentSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId ...

Employing the `instanceof` operator on instances generated by constructors from complex npm dependencies

Context: In one of my npm modules, I've implemented error handling code with a custom error type called CustomError: function CustomError () { /* ... */ } CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = Cu ...

Node's Object.prototype function returns an empty object

When I run Object.prototype in the browser console, I see all the properties and methods within it. However, when I do the same thing in the NodeJS terminal, I get an empty object {}. Can someone explain why this difference occurs? Attached are screenshots ...