Add a blog article to the collection using its specific identification number

I'm currently developing an Express REST API tailored for a dynamic blog management dashboard. I plan to utilize Vue JS as the Front-End, allowing users to authenticate, establish websites, and publish blog posts on specific sites they have created. All data will be stored in Mongo DB Atlas.

Following a foundational guide on constructing a restful api, encompassing CRUD operations and integrating with Mongo DB, has been immensely helpful so far.

The guide demonstrates how to define models, incorporate routes using middleware, and execute GET and POST requests to communicate with the database effectively.

It illustrates a method for incorporating blog posts as individual objects into an array in Mongo DB. The next step is to expand this functionality to group arrays of objects (blog posts) and assign them to specific parent objects while retaining CRUD functionalities for each post.

Presently, my app.js file loads sites and posts as follows:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const slug = require('mongoose-slug-generator');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv/config');

mongoose.plugin(slug);

// Middlewares
app.use(cors());
app.use(bodyParser.json());

// Routes
const postRoute = require('./routes/posts');
const siteRoute = require('./routes/sites');

app.use('/posts', postRoute);
app.use('/sites', siteRoute);

Each route manages the CRUD functions for adding an individual blog post or site successfully.

While straightforward thus far, I am encountering challenges understanding what modifications are required to link a particular blog post to a designated collection object in the database.

The JavaScript file containing routes to add a blog post looks like this:

const express = require('express');
const router = express.Router();
const Post = require('../models/Post');

// Get all posts
router.get('/', async (req, res) => {
  try {
    const posts = await Post.find();
    res.json(posts);
  } catch(err) {
    res.json({message: err})
  }
});

...

module.exports = router;

While this setup functions flawlessly, my ultimate objective is to enable users to POST a specific blog post to a unique object created through my sites model.

Ultimately, I aim to structure the data like this:

[
  {
    "ID": "some unique ID",
    "name": "Example Blog Site 01",
    "enabled": true,
    "blogs": [
      {
        "title": "My blog title",
        "slug": "slug",
        "description": "some blog content"
      },
      {
        "title": "My blog title",
        "slug": "slug",
        "description": "some blog content"
      }
    ]
  },
  ...
]

Each object's blogs array should correspond to my sites.js, serving as the parent object represented by my sites.js route.

This approach empowers users to swiftly generate sets of blog posts under specific endpoints, for example:

Answer №1

Let's tackle this issue by breaking it down into smaller components.

In our scenario, we deal with websites and posts that contain multiple blogs.

Based on my understanding:
A website can house numerous blogs, HOWEVER a blog is tied to a single website only. This establishes a one-to-many relationship.

Before delving further, I recommend checking out the resource here.

One approach to addressing this situation would be:

  • each website should possess a field named postIds, where only the ids of the associated posts are stored.
{
 name: '...',
 postIds: [postId1, postId2...]
}
  • after creating a post, ensure you obtain the id of the newly created post and add it to the postIds of the website with website_id

Effectively, the structure would resemble something similar to this:

// Websites
 [
  { id, name, postIds: [1, 2], ... },
  { id, name, postIds: [3], ... },
]

// Posts
[
 { id: 1, name: 'post 1', ... },
 { id: 2, name: 'post 2', ... },
 { id: 3, name: 'post 3', ... },
]

To retrieve the posts of each website, these references could be beneficial:

Selecting items from an array of ids

Executing an inner join operation

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

Mongo deletion causing backend crashes without any error message

Seeking help with my first ever question, unable to find a solution so here it is. My tech stack includes React, Mongo, Express, and Node. Dealing with PatientDetails.js file. This code snippet demonstrates how I retrieve a specific patient's detai ...

Issue with showing an input field following the button click

I'm having a bit of trouble with this function that should add an input element to a div. I've tried using appendChild and also concatenating the object to innerHTML, but no luck so far. Could it be something my beginner's mind is missing? f ...

Finding the distance between two points in JavaScript requires a simple formula

Here is a code snippet that generates two TRACER points and displays them on a map, as well as shows the union between the two points. <?php $latitudInicio = $_GET['latitudInicio']; $longitudInicio = $_GET['longitudInicio']; $latit ...

Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop? An example of an array-like object would be: let elements = document.querySelector('#someid').children ...

Only focus on the content enclosed within [[xxxx]] and disregard everything else within the string

I'm currently developing a Discord chat bot for the card game "Duelyst". When users type [[CardName]], the bot responds with information about the specific card. The bot is built using an npm package in Node.js. Here's how it's set up right ...

Adjust the iframe height when using slidetoggle

I currently have a menu positioned in the center of the screen, set to "show" by default. Beneath this menu, there is an iframe filling up the remaining space: <script type="text/javascript> $(document).ready(function() { var main_height = ($(d ...

Issue with fetching access token from Azure /oauth2/token endpoint using jQuery, Ajax, or AngularJS due to cross-origin restrictions

I am attempting to obtain an access_token from Azure. Error Message: Unable to fetch : No 'Access-Control-Allow-Origin' header is found on the requested resource. Origin 'http://localhost:61697' cannot access it. Code snippet: fun ...

Dynamic loading of XML data into a DIV when hovering over it

The main idea behind my project is quite simple. I have a grid of company logos extracted from an XML document using XSLT, each logo with its own unique link to the respective company profile. On the same page, I have a separate div that serves as a "prev ...

Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is ...

Trigger ng-model value update on input box by force in JavaScript

<form> Low Range: <input type="number" name="lowRange" ng-model="weight" ng-model-options = "{updateOn:'submit'}"> <button type="submit">Assign</button> <button type="button" ng-cl ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

Dynamic Binding of Checkboxes in Vuex

I am encountering a problem with binding checkboxes using Vuex. Even though I am using v-model with a variable that has a getter and setter to set or get the value in the store, I keep getting incorrect data in the store. The issue arises when I click on a ...

Is there a way to prevent users from downloading PDFs or docs when they are opened in a new tab in a React application?

I recently encountered a situation where I needed PDF files to open in a new tab, but restrict the download for certain users. Despite trying out various third-party packages in React, none of them successfully rendered the PDF files as required. If poss ...

Utilizing variables as parameters inside a JavaScript function

I searched high and low but couldn't find a clear solution to my question. I tried various recommendations without success. Currently, I am working on a script utilizing AJAX, JavaScript, PHP, and MySQL. The goal is to create a functionality where up ...

Display a login/logout button on the navbar of an AngularJS app page based on certain conditions

Welcome.jsp <html> <body ng-app="myApp"> <div class="menu"> <a href="/home"> Home </a> <a href="/orders" ng-show="$scope.isUserLoggedIn"> View Orders </label> <a href="/logout" ng-show="$scope.isUserL ...

A comparison between Angular JSON and JSONP $promise

When making a JSON call from my controller.js: $scope.userInvestors = userInvestors.query({UserID:$scope.user.uid}, function(userInvestors) { console.log("yep yer here"); } Using this $resource: factory('userInvestors', function($resour ...

Upload Avatar Images Without Uploading the Entire Page

Exploring options for integrating an avatar image upload feature into my project. Interested in finding an AJAX/jQuery solution that facilitates seamless image uploading without the need to manually refresh the page post-upload. ...

Differences between encoding URL variables in HREF and using JS window.location for onclick events

For some reason, this particular hyperlink is not functioning properly. I have a Javascript redirect (window.opener.location) where I pass several variables through the URL. The problem arises when these variables contain apostrophes. In PHP, I am using UR ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...