The organizational structure of data in MongoDB for posts, comments, saved content, and likes

I am currently diving into the world of MEANJS web development and working on structuring my data. As a newcomer to the NoSql concept, I am seeking guidance on the best practices to follow.

The data I need to store includes:

questions
answers
likes
saved_questions

Within my application, I offer users the ability to save questions for later viewing and access any answers they have posted. Additionally, I provide statistics for each question such as the number of likes and answers.

My dilemma lies in deciding whether to create one document for "question" and house all related data within it:

{_id: <ObjectId>,
 user_id: <ObjectId>,
 question: 'how can we....',
 answers: [{user_id: <ObjectId>, answer: ''}],
 likes: [{user_id: <ObjectId>}],
 saves: [{user_id: <ObjectId>}]
}

Alternatively, should I create multiple documents for each data type, or perhaps combine both approaches? Your insights would be greatly appreciated.

Answer №1

When setting up a new project, it's essential to have well-defined database models in place. For this, I would recommend creating separate models for the User and the Question. Thankfully, the MEAN.JS boilerplate simplifies this process by offering a pre-built User module with essential authentication functionalities like sign-up, login, and logout. This feature saves a significant amount of time during project deployment.

After setting up the User module, the next step would be to generate a CRUD module for managing Questions using the Yo Generator. This tool streamlines the process by automatically creating and placing the necessary files in the correct directories, along with sample code to guide you through the setup. For detailed instructions on using the Yo Generator, refer to the Yo Generator Section in the MEAN.JS documentation.

To create the Question module, simply run the command yo meanjs:crud-module Question from the root directory of your application. This command generates all the essential files for the database model and adds a new module to both the front and back ends, complete with CRUD functionalities for handling questions.

When defining the database model for questions, navigate to

app/controllers/models/question.server.model.js
and create a Mongoose schema based on your data requirements. An example schema could include fields for title, question content, associated user, answers, likes, and saves.

var QuestionSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true,
        required: 'Title cannot be blank'
    },
    question: {
        type: String,
        default: '',
        trim: true
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    answers: {
        type: Array,
        default: []
    },
    likes: {
        type: Array,
        default: []
    },
    saves: {
        type: Array,
        default: []
    }
});

To enhance the data model further, consider creating separate schemas for related entities like likes, saves, and reports. This allows for storing additional details such as user IDs, dates, and reasons for actions. For more guidance on creating complex Mongoose schemas, refer to the Mongoose Schemas documentation on mongoosejs.com.

For tracking a user's actions, consider implementing separate schemas for each type of action (e.g., comments, likes, saves) and storing relevant details in these schemas. This approach enables efficient querying to retrieve a user's activity history.

By following these steps and customizing the database models to suit your project's requirements, you can effectively manage and organize data within your MEAN.JS application.

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 console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Custom options in MUI Autocomplete are not displaying the selected option

I am currently implementing MUI v5's Autocomplete for a dropdown feature on my website. Within this dropdown, I have options that include both a title and an id. My goal is to store the selected option's id in the state while also updating the d ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

When conducting unit testing with Express, encountering an error message such as "`call of undefined`" may indicate that

In my current quest to test a node.js application using express, I encountered an issue. After successfully returning a simple 404.html page, I attempted to close the node http server, resulting in an error: Fatal error: Cannot call method 'call&apos ...

Tips for efficiently adding a like feature to a MEAN web application

Currently, I am in the process of developing a web application that allows users to express their preferences by liking certain choices displayed on the page. I am trying to optimize the efficiency of the like/unlike system. My main question is whether ev ...

avoid selecting a d3 table

I'm currently learning about creating tables in D3 and I have a question regarding when to use ".select()": For example, when constructing circles: var circles = svg.selectAll("circle") .data(dataSet) .enter() .append("circle") .att ...

Achieving functionality with a fixed header

I am struggling with the scroll functionality and smooth transition in my code for a sticky header. The scroll doesn't work smoothly, especially when the fixed header is activated. The #top-nav-wrapper barely scrolls as expected: <script> $(doc ...

What is the best way to set up a simple example using a Node Stream.Readable?

I am currently exploring the concept of streams and encountering some difficulties in making it work properly. For this scenario, my goal is to send a static object to the stream and then pipe it to the server's response. This code snippet shows my ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Issue with formik onchange event not filling data in Material UI TEXTFIELD component

Greetings! I am currently working on a React project where I am managing the authentication process. I am using Material UI and Formik for validation and handling input changes. However, I encountered an issue with my onchange Formik handler in the TEXTF ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

AJAX seems to be struggling to recognize JSON data as JSON format

I am facing an issue with my AJAX call where the data received from the server is not being treated as JSON, despite setting the datatype to json: function RetrieveMateriasFromServer(callback){ var status_aux; //HTTP request for data from the given UR ...

Switch out everything except for the initial one

Can all instances be replaced except for the first one? For example, 123.45.67..89.0 should turn into 123.4567890. Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index. ...

Creating an Image slideShow with only one Image - making it slide on itself

Apologies for this confusing and vague question. Imagine I only have a single image, and I want to create a slideshow using technologies like Angular, jQuery, JavaScript, or just CSS. What I am aiming for is when the user clicks on my slide button, the i ...

Determine the validity of an image URL using Vue.js

Is there a way to check if an image URL is valid or broken in Vue.js, similar to the process outlined in Angular 2 - Check if image url is valid or broken? ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

PhongMaterial designed specifically for rendering InstancedBufferGeometry

I am working on creating a scene with thousands of simple meshes, and I decided to implement InstancedBufferGeometry for better performance. Most of my code is based on the example provided here: Although instancing works well, it seems to only function p ...

Implementing folder-specific routing in Express js

I'm struggling to figure out how to implement a solution that functions like this code snippet. I need to serve different folders based on various parameters, but I'm hitting a roadblock. An example of this in action would be incredibly helpful. ...

Should I use an array literal or split a string?

Imagine you are in need of a predetermined list of words (the focus here is not on the debate surrounding hard-coding). Would you choose this approach: var items = 'apple banana cherry'.split(' '); Or do you favor this alternative: ...