Tips for building a MongoDB document that includes both objects and arrays, along with the corresponding schema in Mongoose

Need assistance with saving data in a mongodb database such as the following:

{
    name: "Just a name",
    questions: [
        {
            question: "Question 1",
            answerOptions: [
                {id: 0, text: "answer 1"},
                {id: 1, text: "answer 2"},
                {id: 2, text: "answer 3"}
            ],
            correctOptions: [ 0, 2 ]
        },
        {
            question: "Question 2",
            correctAnswers: [ "answer", "another answer" ]
        }
    ]
}
  1. Wondering if it's best to save all data in one collection or should consider decomposing and storing in separate related collections (main, answers, answeroptions, etc)?

  2. If possible to consolidate in one collection, how would a Mongoose schema be structured? Specifically, describing objects and arrays of objects as fields in the Mongoose schema.

Thanks for any guidance!

Answer №1

1. Indeed, considering your specific use case, it is feasible to store data in a single collection without any hierarchical structure. Keep in mind that MongoDB does not support joins, so you will need to manage this within your application logic.

2. Below is the schema I am currently utilizing for my project. The document includes various field types such as arrays of objects:

var mongoose = require('mongoose');

var fieldFive = new mongoose.Schema({
    someField1: String,
    _id:false
});


var someArrayObject = new mongoose.Schema({
    someField1: String,
    someField2: String,
    someField3: false
});


var SampleSchema = new mongoose.Schema({
  fieldOne: {type:String, required: true},
  fieldTwo: String,
  fieldThree: [someArrayObject],
  fieldFour: {someOtherField1:[String], someOtherField2:[String], someOtherField3:[String]},
  fieldFive: {type:{}, ref:fieldFive},
  createdAt: {type: Date},
  updatedAt: {type: Date, default: Date.now},

});

module.exports = SampleSchema;

Hopefully, this information proves beneficial for your project requirements.

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

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

Encountering an unidentified entity within a ReactJS application

Within a container, I've included a search bar inside a form element with two inputs - from and to, along with a submit button. Upon submitting the form, I create an OBJECT named query which looks like this: const query = { from : this.s ...

Creating a Multi-stop Gradient Effect on Lines in THREE.js

Learn how to create a stunning two-color gradient effect on a THREE.js line with this helpful guide: Color Gradient for Three.js line Have you ever wondered how to achieve a multi-stop color gradient along a line in THREE.js? Find out the solution here - ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Is there a way to incorporate the load page plugin specifically for JavaScript while ensuring that my PHP code is still functional?

Is there a way to implement the loading page plugin "PACE" for PHP code execution instead of just JavaScript? I am more comfortable with PHP, CSS, and HTML, but not very experienced in JavaScript/AJAX. The PACE plugin is designed to show a progress bar fo ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

Different ways to eliminate unnecessary items in an array

One task I have is to eliminate all duplicate elements within an array, as shown in the example below: var arr = [ {'seriesIndex':1,pointIndex:0}, {'seriesIndex':1,pointIndex:1}, {'seriesIndex':0,pointIndex:0}, ...

Value-detecting button

Here is some HTML code: <input type="text" id="textbox" value=""> <span id="currenticon">Test</span> <a href="#" id="button">Set</a> <script src="script.js&qu ...

What could be causing the "undefined" property error in my Vue.js component?

In my Vue.js application, I have several components that are structured similarly and are all throwing the same error: TypeError: Cannot read property 'id' of undefined I initially attempted to resolve this issue by enclosing {{ jobs[0].id }} w ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

Is there a way to alter the camera's focal point in THREEJS to focus on a specific object already in the scene?

Currently, I am working with a scene extracted from a THREEJS example (https://threejs.org/examples/webgl_loader_fbx.html) that involves importing and displaying a threejs.json scene. The rendering of the scene works perfectly; I have a grid in place with ...

Issue: Incomplete data retrieval using JS/React fetchDescription: I am facing

I am currently working on an app centered around the card game Magic. The concept involves pasting a list of cards into a textbox and then clicking a button to display corresponding card images. My approach entails using fetch requests to interact with an ...

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

Does Firestore arrayunion offer any kind of callback function?

Hey there! I'm currently working on a voting system and I want to prevent the same user from voting multiple times on the same post. let db = firebase.firestore(); var postRef = db.collection("posts").doc(this.pid); postRef.update({ ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Reorganize the array or generate a new array using the indexes of the objects

I have a specific object that I need to render into table rows and cells using JSX... { "0": [ { "colIndex": 0, "data": { "richTextModule": "Data row 1 cell 1" } }, ...

Error: Realm Subscription Not Found for WRITE Operation - Attempting to Subscribe to Multiple Types Simultaneously

Attempting to configure the realm using the function below. Originally, only the EmailAccount class was present, however, after adding the ApplicationAccount class, writing to the EmailAccount cluster works, but attempting to write to the ApplicationAccoun ...

Retrieve an array of items from the Firebase snapshot

Currently in the process of retrieving items from my Firebase database, I am utilizing a snapshot that is generated when the page loads. I have collected the values of each object in an array and I am now attempting to add an item from each object into a s ...