Mongoose - pushing refs - cannot read the "push" property from undefined

I would like to add a category, and then if it was successful, click on it to collect the user. Here is how I do it:

This is my dashboard.js file, which contains a category outline.

var users = require('./users');

var category = mongoose.model('categories', new mongoose.Schema({
    _id:     String,
    name:    String,
    ownerId: { type: String, ref: 'users' }
}));

router.post('/settings/addCategory', function(req, res, next) {
  console.log(req.body);
  var category_toAdd = new category();
  category_toAdd._id = mongoose.Types.ObjectId();
  category_toAdd.name = req.body.categoryName;
  category_toAdd.ownerId = req.body.ownerId;

  category.findOne({
    name: req.body.categoryName,
    ownerId: req.body.ownerId
  }, function(error, result) {
     if(error) console.log(error);
     else {
       if(result === null) {
         category_toAdd.save(function(error) {
           if(error) console.log(error);
           else {
             console.log("Added category: " + category_toAdd);
<<<<<<<<<<<<<<<<<<<THE CONSOLE LOG WORKS GOOD
             users.categories.push(category_toAdd);
           }
         });
       }
     }
  });

Here is my users.js file that contains the users schema.

var categories = require('./dashboard');

var user = mongoose.model('users', new mongoose.Schema({
    _id:          String,
    login:        String,
    password:     String,
    email:        String,
    categories:   [{ type: String, ref: 'categories' }]
}));

So the add proccess category works well and I can find the category in the database. The problem is that I'm trying to push a category to the user.

This line:

users.categories.push(category_toAdd);

I get this error:

Cannot read property "push" of undefined.

I need to admit once again that before this press comes console.log, where the category is printed correctly.

Thank you for your time.

+4
source share
1

users - Mongoose, . users.

dashboard.js

...
category_toAdd = {
  _id: mongoose.Types.ObjectId(),
  name: req.body.categoryName,
  ownerId: req.body.ownerId
};

// Create the category here. `category` is the saved category.
category.create(category_toAdd, function (err, category) {
  if (err) console.log(err);

  // Find the `user` that owns the category.
  users.findOne(category.ownerId, function (err, user) {
    if (err) console.log(err);

    // Add the category to the user `categories` array.
    user.categories.push(category);
  });
});
+3

Source: https://habr.com/ru/post/1624655/


All Articles