Creating a Mongoose model with an array property that includes instances of the same model as the parent

My current challenge involves creating a Note object with a subnote property that should be of the same type as the parent model. Currently, I have achieved this by creating two identical models with different names and having them reference each other. Here is an example of how I'm doing it:

Note schema:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const noteSchema = new Schema({
  icon: {
    type: String,
  },
  banner: {
    type: String,
  },
  name: {
    type: String,
    required: true,
  },
  user_id: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    required: true,
    default: Date.now,
  },
  sub_note: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "sub_notes",
  },
  content: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "blocks",
    },
  ],
});

module.exports = Note = mongoose.model("notes", noteSchema);

SubNote schema:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const subNoteSchema = new Schema({
  icon: {
    type: String,
  },
  banner: {
    type: String,
  },
  name: {
    type: String,
    required: true,
  },
  user_id: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    required: true,
    default: Date.now,
  },
  sub_note: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "notes",
  },
  content: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "blocks",
    },
  ],
});

module.exports = SubNote = mongoose.model("sub_notes", subNoteSchema);

I am uncertain if the aforementioned method is the correct approach. Any guidance would be greatly appreciated. Thank you.

Answer №1

To achieve this task, you can follow these steps:

const noteSchema = new Schema({
 
  sub_note: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "notes",
  },

});

module.exports = Note = mongoose.model("notes", noteSchema);

Another way to accomplish this is by using the "this" keyword.

const noteSchema = new Schema({
 
  sub_note: this

});

module.exports = Note = mongoose.model("notes", noteSchema);

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 are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

The mediator's location becomes uncertain after the route is manually adjusted

Currently, I am working on developing a single-page-application that utilizes passport local authentication. The user is authenticated and returned within the app.post "/login" route. Once the user object is obtained, I store it in Chaplin.mediator.user (s ...

Error: An unexpected issue occurred when attempting to iterate over the snapshot

I recently started exploring nodejs and Google Cloud FireStore. Below is the code that I am currently working on. createNewPage = function (title, header, content, db ) { let pageRef = db.collection("pages").doc(title.trim()); let setPage = pag ...

modify the username in the Mongoose data model

I am looking to provide users with the ability to update their usernames in the mondgod database. My database is set up using mongoose as ODM, and here is the schema for my user: UserSchema = new mongoose.Schema({ username: String, phone: { ...

What is the best way to manage the package-lock.json file during deployment from git using SSH?

In my deployment process, I utilize a Git repository to check code in. By using web hooks, a deployment script is triggered on the production server. Once connected to Git via SSH and a .pem key on the server, I perform a Git pull, npm install, webpack bui ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Exploring the integration of PostgreSQL into JavaScript

As a beginner in JavaScript, I am looking to create a web page that can store data in a database. Can anyone provide guidance on what resources or materials I should study to learn more about this process? ...

Merging nested loop queries into a parent array output with pg-promise

As I navigate my way through node(express) and pg-promise, I find myself struggling to integrate the results of nested queries into the main JSON array result query. In my database, I have two tables: Posts and Comments. CREATE TABLE post( id serial, con ...

What could be causing the 'npm run build' command to take over 30 minutes on the development server, but less than a minute on my local machine?

My experience with npm and webpack is limited, but I am facing a peculiar situation. A small project that builds quickly on my local machine takes an extremely long time to run on our test server. In the package.json file, the script looks like this: "scr ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

Transferring Information from Angular Interface to NodeJS through a JSON Document

I am currently working on establishing a connection between an AngularJS front end and a NodeJS back end application. The main objective is to manipulate data in a JSON file instead of a traditional database. I have attempted to set up the post method on ...

How can I prevent Heroku from automatically running the script with 'npm start'?

I am currently in the process of developing a server-based application that utilizes automated scripts, also known as "bots," within a cloud environment. I have set up Heroku Scheduler to execute one of these scripts automatically, as illustrated in Figure ...

When trying to use express, the error message "d3.scale is

Having trouble integrating a c3-chart into my web application using node.js and express. The c3.js file is throwing the error message: TypeError: d3.scale is undefined Here is an excerpt from my layout.yade file: doctype html html head title= titl ...

Start Node-Red and use the Selenium driver

Running mocha test suite to test a node-red nodes involves using mocha and the selenium driver. I encountered an issue while running the node-red module. When I start the test with $ mocha --ui **tdd**, the node-red application is unable to locate my flow ...

in node.js, the request's body property is not set

When I make a post request from my AngularJS to Node.js, the request.body is coming back as undefined. However, I am able to receive values when using the get method. Here is my AngularJS code: app.controller('create_company', function($scope, ...

What causes the Error: ENOENT open error to occur when attempting to render a doT.js view?

My first experience with doT.js led me to create a basic server setup: 'use strict'; var express = require('express'); var app = express(); var doT = require('express-dot'); var pub = __dirname+'/public'; var vws ...

Making an Ajax call with Angular

I am completely new to Angular JS. Currently, I am attempting to create an alert in Angular and also wishing to send an AJAX request to a Node server. Below is the code I have been working on: However, I am encountering an issue with my alert not functio ...

Leveraging GridFS-Stream to transfer image files to the Front-End React.js via Axios - Encoding chunks into base64 strings

I have managed to successfully upload my image file to MongoDB using Multer and Multer-Gridfs-Storage, however, I am encountering difficulties when trying to retrieve it. After attempting to retrieve the data with GridFS-Stream, I encountered a similar is ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...

Having trouble with eslint in create-react-app because of a parent folder that also has another app with its own node_modules folder?

I have a git repository with two projects inside: a loopback app (named app) and a create-react-app react app (named client). Here is the directory structure: ├─┬app │ ├──node_modules │ ├─┬client ├─node_modules The loopback ...