Adding a fresh element to an array in a mongoDB document

After researching various SO posts, I have come across different methods to achieve this task. Hence, I am curious to know which approach is considered the most preferable. Since I am instructing students, it is important for me to teach them best practices.

If we consider the following BlogPost object (Simplified):

var BlogPostSchema = new mongoose.Schema({
    body: String,
    comments: [String]
});

and the goal is to add a new comment to the array of comments for this blog, I can think of at least 3 main ways to accomplish this:

1) In Angular, push the comment to the blog object and then submit a PUT request to the /blogs/:blogID endpoint to update the entire blog object with the new comment included.

2) Make a POST request to a /blogs/:blogID/comments endpoint where the request body solely consists of the new comment. Retrieve the blog, push the comment to the array using vanilla JS, and save it:

BlogPost.findById(req.params.blogID, function(err, blogPost) {
    blogPost.comments.push(req.body);
    blogPost.save(function(err) {
        if (err) return res.status(500).send(err);
        res.send(blogPost);
    });
});

OR

3) Send a POST to a /blogs/:blogID/comments endpoint with the new comment in the request body, and then utilize MongoDB's $push or $addToSet to add the comment to the array:

BlogPost.findByIdAndUpdate(
    req.params.blogID,
    {$push: {comments: req.body}},
    {safe: true, new: true},
    function(err, blogPost) {
        if (err) return res.status(500).send(err);
        res.send(blogPost);
    });
});

I came across a helpful StackOverflow post, where a user discusses the pros and cons of option 2 versus option 3, suggesting that option 2 is simpler and recommended whenever possible. (Also, avoiding methods that may limit the use of hooks and other mongoose features.)

What are your thoughts on this? Any advice you would like to share?

Answer №1

When it comes to application perspective, point 3 stands out as the superior option. Here's why:

  1. The query itself clearly defines the goal we are aiming to achieve, making it easily understandable.
  2. The save function is unpredictable in terms of what changes it may make, introducing uncertainty.
  3. Manipulating a document before saving it poses a risk of unintentionally altering other fields, which doesn't apply to point 3.
  4. In the case of addToSet, the previous point is more apparent.
  5. Considering concurrency issues, if multiple calls are made with different comments for the same blog while using option 2, there's a possibility that changes could be overwritten. Option 3 offers a safer solution in such scenarios.

Performance-wise, both options yield similar results, so any visible differences may be minimal or nonexistent. However, option 3 leans towards being safer and cleaner in practice.

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

The function is missing a closing return statement and the return type does not specify 'undefined'

It seems like the function lacks an ending return statement and the return type does not include 'undefined'. In a recent refactoring of the async await function called getMarkets, I noticed that I had mistakenly set the return type as Promise: ...

When updating the innerHTML attribute with a new value, what type of performance enhancements are implemented?

Looking to optimize updating the content of a DOM element called #mywriting, which contains a large HTML subtree with multiple paragraph elements. The goal is to update only small portions of the content regularly, while leaving the majority unchanged. Co ...

Creating an HTML button that will execute JavaScript code when clicked

My goal is to create a button that, when clicked, updates the background of another div. These buttons are dynamically generated using PHP from images in a folder. <!DOCTYPE html> <html> <head> <meta charset="UTF-8> <scr ...

Update the background image every minute with a smooth transition effect

I am currently in the process of developing a personal dashboard that requires dynamic background images to change every minute. To achieve this functionality, I have integrated the [Pixabay API][1] and formulated the following API request: https://pixaba ...

The checkbox will be automatically checked whenever there is any modification in the textbox

I'm currently working on a Grid view with a checkbox and two textboxes. What I want is for the checkbox to be automatically checked whenever there is a change in one of the textbox values, for example switching from 0 to 1. This project is being devel ...

Checklist options controlled by dropdown menus

I am facing a challenge with a collection of checkboxes that represent settings for equipment displayed on a page. The checkboxes are populated using ObjectdataSource and an IEnumerable method to bring distinct settings. Additionally, I have created a drop ...

ways to dynamically retrieve input values in PHP

Is there a way to dynamically add and remove data fields, as well as increase and decrease fields dynamically in PHP? I am looking to retrieve the subject value in an array or JSON format using PHP only. https://i.stack.imgur.com/HqDCz.png <div data-ro ...

"Reinvigorating Listboxes in AngularJs for Enhanced User Experience

I currently have two multiple listboxes set up as follows: When I select multiple values from the left listbox and click the right arrow, those values will be moved to the right listbox and removed from the left listbox. HTML <select multiple ng- ...

What steps should be taken to prepare files (such as editing images) before they are uploaded to Google Drive using the `rpldy/drive-uploady` tool?

I have successfully implemented rpldy/drive-uploady to upload files to Google Drive. However, I would like to allow users to edit images before uploading them. How can I achieve this? Below is the code snippet: import DriveUploady from "drive-uploady ...

Converting Indic Characters to Unicode Escaped Characters: A Step-by-Step Guide

In the process of developing a mobile application specifically for Android that focuses on content in the Local Indic Language, Tamil. The translation equivalent of 'Welcome' in Tamil is: வணக்கம். However, since Android does not sup ...

Add a new value to an object and ensure that only the unique value is appended to the first

I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its kind. Obj1 [{ buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 // add new key valu ...

Tips for transitioning from GWT to AngularJS

Since the development plugin has been discontinued, GWT development feels less enjoyable. Each small modification results in long recompilations and debugging a mix of Java and Javascript in the browser. I'm considering transitioning to AngularJS. Ca ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

vee-validate - Standalone form validation with distinct procedures

I currently have a situation where I am dealing with two forms, each in separate steps and having their own submit button. Using $validator.validateAll() validates all the inputs on the page, but I specifically need validation for each form individually. ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Can a new frame be created below an already existing frame in HTML?

My main.html file looks like this: ----- main.html---------------- <title>UniqueTrail</title> <script src="main.js"></script> <frameset rows='200,200'> <frame id='one' src="f ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

Tips for accessing the most recent embedded document added using the push() method

I'm having difficulty determining the feasibility of this situation. While using the mongoose blog example to illustrate, my specific use case is a bit more complex: var Comments = new Schema({ title : String , body : String , date ...

Simple Timer App with Vanilla JavaScript

Hey there! I am a newcomer to JavaScript and recently joined the stackoverflow community. Currently, I am working on a project called Pomodoro Timer with the goal of creating something similar to this example: http://codepen.io/GeoffStorbeck/full/RPbGxZ/ ...

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...