Mongoose - 推送参考 - 无法读取未定义的属性“推送”

elz*_*zoy 5 push ref undefined mongoose mongodb

我想添加一个类别,然后如果成功,将它的引用推送到用户的集合。这就是我这样做的方式:

那是我的“dashboard.js”文件,其中包含类别架构。

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);
           }
         });
       }
     }
  });
Run Code Online (Sandbox Code Playgroud)

这是我的“users.js”文件,其中包含“users”模式。

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' }]
}));
Run Code Online (Sandbox Code Playgroud)

因此,类别添加过程运行良好,我可以在数据库中找到该类别。问题是当我尝试将类别推送给用户时。

这一行:

users.categories.push(category_toAdd);
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Cannot read property "push" of undefined.
Run Code Online (Sandbox Code Playgroud)

我需要再次承认,在推送之前有 console.log 正确打印了类别。

谢谢你的时间。

gne*_*kus 6

users对象是 Mongoose 模型,而不是它的实例。您需要users模型的正确实例来添加类别。

仪表板.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's `categories` array.
    user.categories.push(category);
  });
});
Run Code Online (Sandbox Code Playgroud)