When establishing a many-to-many relationship in Mongoose, the use of populate() may not be suitable

I am facing an issue while trying to establish a many-to-many relationship using mongoose for employee creation. When I call the .post method, I encounter the following error:

TypeError: Employee.create(...).populate is not a function

Interestingly, my .get method which also utilizes .populate runs without any errors. This discrepancy has me puzzled about why the .post method is throwing an error. Here is the relevant code snippet:

app.route('/api/employees')
    .get(function (req, res, next) {
        Employee.find()
          .populate('statuses')
          .exec(function (err, employee) {
            if (err) {
              return next(err);
            }

            res.json(employee);
        });
    })
    .post(function (req, res, next) {
        Employee.create(req.body)
        Employee.findById(req.params._id)
          .populate('statuses')
          .exec(function (err, employee) {
            if (err) {
              return next(err);
            }

          res.json(employee);
        });
    });

Below is the definition of the status class:

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

var statusSchema = new Schema({
  name: ['In office', 'Project', 'Fired', 'Resigned', 'Ill']
});

module.exports = mongoose.model('Statuses', statusSchema);

And this is how the employee class is defined:

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

var employeeSchema = new Schema({
  name: String,
  division: ['IT','System','Trainee','Intern'],
  statuses: [{type:Schema.Types.ObjectId, ref: 'Statuses'}],
  project: Boolean,
  comment: {type:String, default:null}
});

module.exports = mongoose.model('Employees', employeeSchema);

The .post method seems to be causing a 500 error as well, leading me to wonder if there might be some connection between the two issues. Can you spot any obvious error in the above code, or should I investigate elsewhere for potential mistakes?

Answer №1

In the post request, one crucial mistake was not saving the state before proceeding. It is essential to save the state in order to save the status._id in the statuses array. After that, you should use findById to locate the employee._id and then populate it.

For a clearer understanding, here is an example:

Status.create(req.body, (err, status) => {
  if (err) console.error(`Error ${err}`)

  Employee.create({
    name: req.body.name,
    comment: req.body.comment,
    division: req.body.division,
    name: status._id
  }, (err, employee) => {
    if (err) console.error(`Error ${err}`)

    Employee
    .findById(employee._id)
    .populate('statuses')
    .exec((err, employee) => {
      if (err) console.error(`Error ${err}`)

      // console.log(JSON.stringify(employee))
      res.json(employee);
    })
  })
})

Answer №2

After the creation of an object in mongoose, populating is not an option. visit Documentation

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

Is there a way to retrieve the headers from an HTTP response in JavaScript that wasn't initiated by an AJAX request?

I have a login page setup to send an HTTP post request to the server, which then redirects me to another page on the server in the response message. On this new page, I need to access the location header to obtain a specific value for future server tasks. ...

Tips on managing the onKeyUp event in a ReactJS form

Here is a simple JavaScript function called numericOdds implemented in home.js file: function numericOdds(e) { var valid = /^[1-9]{1}[0-9]{0,1}$/ var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/ var lastValid = ''; var n; console.log(&apo ...

How can I resolve the error message "undefined prompt" when using node in the command line interface?

When attempting to execute a simple javascript program via the command line, I encountered an unexpected error. The prompt function is normally a straightforward javascript command, which is why I am puzzled as to why it is not defined. This is what my te ...

Incorporate an additional section into the Typegoose subdocument

Is there a way to add an extra field to the User class subdocument? class Car { @prop() public model?: string; } class User { @prop() public name?: string; @prop({ required: true }) public age!: number; @prop({ ref: () => Car }) publ ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

Ways to troubleshoot the issue of a non-working "Onclick function"

let username; document.getElementById("mySubmit").onclick= function(){ username= document.getElementById("myText").value; document.getElementById("myH1").textContent= `Hello ${username}` } <!DOCTYPE html> <html lang="en"> <head> < ...

Highlight the title with a stylish CSS animation effect

I have a challenge with animating div tags once they come into view on the page. Thanks to waypoint.js, I have successfully achieved the 'in viewport' trigger, but now I need help with the animation part. Specifically, I am looking to add a grey ...

Guide for linking together multiple Axios calls to ensure they execute in sequence and enable each call to access the data obtained from the preceding call

Hey everyone, I have a unique challenge that requires your help. So, I'm working with an array of items and I need to make an Axios post for each item in the array. The catch is that each item relies on data returned from the previous one, so they mus ...

Invoke a dynamic python function once the webpage has finished loading in a Django application

I have a unique function in Python that is able to return various Image URLs. I am looking to incorporate a button on a Django-built webpage that can dynamically change the image source based on the returned value from the function. However, the challenge ...

Heroku deployment of Node.js and React: The app does not have a default language specified

My attempt to deploy my first project on Heroku, which combines Node, React, and MongoDB with Mongoose, is running into an issue. When I use the command git push heroku master, I encounter this error: remote: Building source: remote: remote: ! No def ...

Creating support for tables in Draft.js

I am currently working on creating support for tables (one level deep) using draft.js One crucial requirement I have is that all existing editor functionality must work seamlessly within these tables I present three options for consideration, please sele ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

"An exclusive event scheduled for one day only on the Bootstrap calendar for the year

clickDay: function(e){ addEvent({ date :e.date}); } When a user clicks on a day in the calendar, a modal will open. However, I want to ensure that only one event can be added per day, meaning the modal should not open if the user clicks ...

I'm unable to scroll back up after making an ajax request, as the code automatically scrolls to the bottom of the div

I'm currently working on implementing a JavaScript code to automatically scroll to the bottom of a div after an AJAX request is made. However, I've encountered an issue where I am unable to scroll back up because my JavaScript is constantly check ...

Locate the initial ancestor element that contains a specific child element on the first level

Looking to retrieve the primary parent element of a selected item that contains a checkbox as a direct child. HTML $('input[type="checkbox"]').change(function(e) { $(this) .parent() .parents("li:has(input[type='checkbox'] ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

Is there a way to control the quantity of items being displayed in my ng-repeat directive?

Here are the objects in my array: 01-543BY: Array[1] 03-45BD23: Array[1] 03-67BS50: Array[1] 06-78FR90: Array[1] 07-467BY3: Array[1] 09-23DF76: Array[1] Currently, I have a total of six objects, but I only want to display four. This is how I am using ng- ...

When preparing for deployment, issues may arise with the module package.json

Encountering an issue with the production build - when running "cross-env NODE_ENV=production API_V=production npm run build," I'm getting an error from react-player: ERROR in ./node_modules/react-player/lib/ReactPlayer.js Module build failed: Re ...

Struggling to adjust the width of a div accurately following the population of AJAX content

This particular piece of code is responsible for populating an inner div within an image slider by making an Ajax call : $.ajax({ type: "GET", dataType: 'json', url: $(this).attr('href') }).done(function (result) { ...