`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue?

Here is my product schema:

mongoose = require('mongoose');
var Schema = mongoose.Schema;

var productSchema = new Schema({

cd: {
    type: Number,
    require: true
},

nm_iten: {
    type: String,
    require: true
},

type_iten: {
    type: String,
    require: true
},

unity: {
    type: String,
    require: true
},

});
var product = mongoose.model('Product',productSchema);
module.exports = {product:product}

And, here is my purchase schema:

   var mongoose = require('mongoose');
   var Schema = mongoose.Schema;
   var productSchema = require('./products');
   var product = productSchema.product;

   var purchaseSchema = new Schema({

     code: {
       type: Number,
       require: true
    },

     product:[product],

     quant: {
       type: Number,
       require: true
    },

    vl_uni: {
       type: Number,
       require: true
     },

     vl_total: {
        type: Number,
        require: true
    }


    });
    mongoose.model('Purchase',purchaseSchema);

Answer №1

When creating a purchase schema, it is important to ensure that the product field points to the productSchema and not directly to the product model.

Below is an example of the Product schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
    cd: {
        type: Number,
        required: true
    },    
    nm_iten: {
        type: String,
        required: true
    },       
    type_iten: {
        type: String,
        required: true
    },        
    unity: {
        type: String,
        required: true
    },   
});
module.exports = productSchema;

And here is how you can define the Purchase schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = require('./products');
const product = productSchema;

const purchaseSchema = new Schema({
   code: {
       type: Number,
       required: true
   },
   product:[product],
   quant: {
       type: Number,
       required: true
   },
   vl_uni: {
       type: Number,
       required: true
   },
   vl_total: {
       type: Number,
       required: true
   }
});
mongoose.model('Purchase',purchaseSchema);

If you need more information on embedded documents in MongoDB, check out the documentation at: http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html

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

Unable to utilize routes in Express.JS when integrated with nginx

After setting up nginx in front of Express.JS, everything seemed to be running smoothly. However, I encountered an issue when trying to access website.com/users, which resulted in a 404 Not Found error. It appears that accessing website.com works fine, but ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

What is the best way to route a localpath to a different page including parameters in Nuxt Js?

Hello, I am facing an issue where I need to pass parameters in the URL to another page in NuxtJs props: { idPending: { type: Number, required: true } }, methods: { fetchpage() { const orderId = this.idPending; this.$rou ...

Issue with ForwardRef component in Jest for React Native testing

When attempting to write a test case for my Post Detail screen, I encountered an error that stated: error occurred in the <ForwardRef> component: Here is my test class code: import React from "react"; import { NewPostScreenTemplate } from ...

Issue with useState in Next.js when fetching data from an API

When attempting to retrieve data from the API, I am receiving a response. However, when trying to set the data to useState using the setAccessData function, the data is not being accessed properly. Despite trying multiple methods, the data continues to sho ...

The error message "res.jwt is not a function" is commonly encountered when using Node

I kept receiving the error message: res.jwt is not a function I have installed jwt-express and imported it like this: import jwt from 'jwt-express' This is my auth.js file: import Account from '../services/account.js' import env from ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...

How can I effectively save data to a session using connect-redis?

I am looking to save the username of an account into session storage. I am currently using node.js with the expressjs framework and have attempted to utilize connect-redis for storing sessions, following a tutorial on expressjs. Can someone please guide ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

Text parsing with jQuery

Hello fellow developers. I am interested in creating a text parser using jQuery. My goal is to develop a function that can take a string as input and convert it accordingly. Imagine we have a div with the following HTML structure: <div class="item"> ...

Struggling with a minor glitch in a straightforward coin toss program written in JavaScript

I'm a newcomer to JavaScript programming and I am struggling with understanding how the execution flow is managed. I attempted to integrate an animation from "Animation.css" into a coin toss program, but encountered an issue. When trying to use JavaSc ...

There seems to be an issue with the sorting functionality in Mongoose

Why doesn't sorting work with Mongoose? I have searched extensively but still can't figure it out. Every time I attempt to implement it, it fails. Here is the code snippet in question: Pics.find({}).limit(8).populate('creator').sort("c ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Ways to efficiently implement configuration settings in a functional approach

I've delved into the world of functional programming and I'm working on developing a package that needs to be configurable. My goal is to set up this configuration only once to maintain purity in my functions without relying on global state. Curr ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

Using AngularJS date picker to set value in Spring model setter

When using AngularJS with Spring, I noticed a discrepancy in the date values between my view file and the POJO User object. In my view file, I have used an input type date to bind the "user.dateOfBirth" attribute. When I select a date, it is displayed cor ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...