Error encountered in pre-middleware hooks when querying Mongoose model with findById due to foreign model reference

Within this scenario, I have two distinct models: Protocol and Comment. Each model incorporates a middleware ('pre' or 'remove') that triggers the other model. The issue arises when attempting to call the Comment middleware in Comment.js as it halts at Protocol.findById(). This is due to Protocol being recognized as an object rather than a model function.

Protocol : [object Object] Type : object

Upon removing

const Comment = require('../models/comment')
from Protocol.js, the Comment.js middleware functions correctly. Subsequently, Protocol within it is displayed as follows by the console:

Protocol : function model(doc, fields, skipId) {
  model.hooks.execPreSync('createModel', doc);
  if (!(this instanceof model)) {
    return new model(doc, fields, skipId);
  }
  Model.call(this, doc, fields, skipId);
} Type : function

The behavior exhibited here is perplexing. Even more puzzling is the fact that while the Protocol.js middleware operates flawlessly, despite Comment.js containing

const Protocol = require('../models/protocol')
.

A workaround was discovered in another discussion thread, recommending to substitute Protocol.findById() within the middleware with

mongoose.model('Protocol').findById()
. However, this resolution fails to address the root cause of the problem.

Below are the scripts provided. If additional information is required, kindly let me know, and I will furnish it promptly. Thank you.

Protocol.js model & middleware

// Dependencies
const mongoose = require('mongoose')

//Models
//<!---- If Comment is not required here then the Comment Middleware works ---->!
const Comment = require('../models/comment')

//Schema
const protocolSchema = mongoose.Schema({
    _id : mongoose.Schema.Types.ObjectId,
    title:  {
        type : String,
        required: true
    },
    comments : [{
        type: mongoose.Schema.Types.ObjectId,
        ref : 'Comment',       
    }]
})

//Middleware Hook Call
protocolSchema.pre('remove', async function() { 
    console.log('Starts Protocol.schema.pre(\'remove\')')

    var toBeDeletedProtocol = this

    await removeComments()

    function removeComments(){
        return new Promise ((resolve, reject) => {
            console.log('Starts removeComments()')
            var deletedComments = []

            Comment.find({protocol : toBeDeletedProtocol._id})
            .exec()
            .then( comments => {
                console.log('comments found: ' + comments)
                return resolve()
            })
            .catch(err => {
                console.log('Removing comment(s) related to the deleted protocol failed in protocol remove Hook')
                return reject(err)
            })
        })
    }
}) 

//Model Export
module.exports = mongoose.model('Protocol', protocolSchema)

Comment.js model & middleware

//Dependencies
const mongoose = require('mongoose')

//Models
const Protocol = require('../models/protocol')

//Schema
const commentSchema =  mongoose.Schema(
    {
        _id : mongoose.Schema.Types.ObjectId,
        content: {
            type: String, 
            required : true
        },
        protocol : {
            type: mongoose.Schema.Types.ObjectId,
            ref : 'Protocol',
            required : true,
        }
    }
)

//Middleware Hook Call
commentSchema.pre('save', async function() {
    console.log('Starts Comment.schema.pre(\'save\')')

    var toBeSavedComment = this

    await updateProtocol()

    function updateProtocol(){
        return new Promise ((resolve, reject) => {
            console.log('Starts updateProtocol()')

            console.log('toBeSavedComment : '+ toBeSavedComment) 
            console.log('Protocol : '+ Protocol, 'Type : ' + typeof Protocol)        
            //<!----- the ERROR occurs here -----!>
            Protocol.findById(toBeSavedComment.protocol)
            //<!----- Protocol is seen as an object instead of a model function -----!>
            .exec()
            .then( protocol => {
                console.log('protocol found : ' + protocol)
                return resolve()
            })
            .catch(err => {
                console.log('Error in updateProtocol() in Comment.schema pre \'save\'') 
                console.log(err)
                return reject(err)
            })

        })
    } 

})    
//Export
module.exports = mongoose.model('Comment', commentSchema

)

Package.json

{
  "name": "debug",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "mongoose": "^5.3.2",
    "nodemon": "^1.18.4"
  }
}

Answer №1

It's been a while and I haven't encountered the same issue again, so I still don't have a definitive solution. However, I have identified a mistake that may be causing this unexpected behavior. I was concatenating variables or objects in console.log, like this:

console.log('toBeSavedComment : '+ toBeSavedComment) 
console.log('Protocol : '+ Protocol, 'Type : ' + typeof Protocol)

Instead, use commas "," like this :

console.log('toBeSavedComment : ', toBeSavedComment) 
console.log('Protocol : ', Protocol, 'Type : ' , typeof Protocol)

Concatenating objects in console.log, for example in Amazon Web Service: Elastic Beanstalk can cause issues with API compilation.

This isn't a definitive answer, but I hope it provides some insight!

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 process of integrating hegel.js with a React application created using create-react-app?

Have you heard of Hegel.js? It's a powerful type checker that I recently discovered. Surprisingly, there isn't much information online about using hegel.js with React. Check it out at ...

Node.js/Express.js is throwing an error: 'undefined is not a function'

I recently started using 'express-namespace' to organize my routing in a cleaner way. Below is the snippet of code I have implemented. .. 9 var controllers = require('./controllers'); 10 require('express-namespace'); .. 46 ...

The CORS policy has prevented access: The requested resource in the express react client does not have the necessary 'Access-Control-Allow-Origin' header

I've tried various links, tutorials, and documentation but I feel like I'm just spinning my wheels and not making any progress. Server code: const express = require('express') const cors = require('cors'); const app = expre ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

The current registry configuration does not provide support for audit requests when running npm audit

I am facing an issue with one of my dependencies that is in the form of "protobufjs": "git+https://github.com/danieldanielecki/protobufjs-angularfire.git#master". I installed it using npm install --save https://github.com/danieldanielecki/protobufjs-angula ...

Using Node.js, Express, and MongoDB, what is the most effective way to implement a count query in an array of object arrays

In my application, there are two models: User and Item. Each User is assigned an array of 5 items. Users have the ability to classify their items as Qualified, Not Qualified, or leave them unclassified. Here are the model schemas: const ItemSchema = new Sc ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

Tips for using nodemon to automatically restart multiple server files in npm script when making changes to the files:

Whenever I make edits to a file in the specified folder, I need the two server files to restart using nodemon within an npm script. Below is the npm script: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": ...

The for loop unexpectedly interrupts a different array

Hey there, I've been working with puppeteer and came across an issue with the following code snippet: console.log(dealsId[i]); for (var i = 0; i < sizes.length; i++) { var refIdClasses = await sizes[i].$eval('input', a => a.getAtt ...

Are JWT authentication methods secure and how do they help protect against CORS vulnerabilities?

I have recently implemented token-based authentication in my project rather than using cookie-session based authentication. With JSON Web Tokens (JWT), every time I send a request to the server, I attach the token in the headers and validate it against t ...

Displaying a view without using res.render

According to the given instructions: https://github.com/ericf/express-handlebars In my current scenario, I require template compilation without using res.render('myView') as there is no res available in my context. This is my approach so far: ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

Issue with NPM linked module flagged as missing requirement

Currently, I am linking my-lib to observe immediate effects in my-app. cd my-lib-folder npm link cd ../my-app-folder npm link my-lib The process works as anticipated. Changes made are detected by my-app and a symlink is visible in the node_modules direc ...

Can you show me the method to retrieve the value of client.query in Node JS using PG?

I have been working with node.js to establish a database connection with postgresql. Here is what my dbConfig.js file looks like: var pg = require('pg'); var client = new pg.Client({ host:'myhoost', port:'5432', ...

Uniting backend (Express) and frontend (Angular) paths for seamless navigation

I'm considering hosting both the Angular app and its backend on the same host (not sure if this is a good idea!). To achieve this, I created a web folder within a NodeJS (express) app and moved the deployed Angular files there. Additionally, I config ...

Activity Timeout in Azure Durable Functions

Within my activity function, I have the following code block: do { await timeout(500); } while (await getStatus() === false); Here's what each part of the code does: function timeout(ms) { return new Promise(resolve => setTimeout(reso ...

Encountering a React npm start issue following the installation of MongoDB

I've been engaged in a simple project to get more familiar with react. I made the decision to incorporate mongoDB into my project, but since installing it, my app refuses to start. The odd thing is that I haven't even added any code for my app to ...

Spreading out across various tiers proves to be ineffective

I've encountered a challenge with my blog model that contains multiple comments with nested replies. So far, I have only been able to access the first two layers of these comments. Here is an example of how this data is stored in my database as Comme ...

Using Java to implement an embedded document structure in MongoDB through REST APIs

I am currently developing a REST service in Java that utilizes MongoDB (specifically the `mongodb-java-driver`), Jersey, and Jackson. One of the classes I am working with is the Employee class. public class Employee extends BasicDBObject { public Empl ...

Having difficulty submitting a POST request in a NodeJS and ExpressJS application

I have developed three variations of my NodeJS app. The first version solely relies on Node and is functioning properly. However, the second and third versions of the app, which utilize ExpressJS, are encountering issues. I had to switch to using Express ...