【问题标题】:mongoose model.update not working猫鼬模型.更新不起作用
【发布时间】:2018-01-15 20:53:50
【问题描述】:

它以前可以工作。不知道有什么变化... 方法是这样的:

用户有一组团队。删除团队后,我希望也将 RefID 从用户的团队数组中删除

TeamSchema.pre('remove', function(next) {
  const team = this;
  User.update( { teams: { $in: [team._id] } }, { $pull: { teams: team._id } }, next);
});

收到此错误:

(node:7484) UnhandledPromiseRejectionWarning: UnhandledPromiseRejectionWarning: Unhandled Promise Rejection (rejection id: 1): TypeError: User.update is not a function

此外,其他方法都不能正常工作(Model.findById, Model.find 等...),尽管我确实在文件顶部导入了我的模型和猫鼬。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = require('./user');

不知何故,我的 mongoose 操作在 Model.pre() 函数中不起作用。

我有另一个带有pre 方法的文件,其中Model.find 函数起作用:

UserSchema.pre('remove', function(next) {
  const user = this;
  Team.find({ admin: { $in: [user._id] } }, function(err, teams) {
    if (err) {
      return next(err);
    }
    teams.forEach(function(t) {  t.remove(); });
    next
  });
});

有人熟悉这个问题吗?

【问题讨论】:

  • 如果您需要来自架构文件的同一文件夹的user,您确定您不会意外地需要user schema 而不是user model?在那里打个断点,看看User.update是不是猫鼬模型。

标签: node.js mongodb mongoose middleware


【解决方案1】:

您可以尝试使用mongoose.models[modelName] 代替直接型号名称。像下面这样

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

var UserSchema = new Schema({
     // .....
    })

UserSchema.pre('remove', function(next) {
  const user = this;
  mongoose.models['Team'].find({ admin: { $in: [user._id] } }, function(err, teams) {
    if (err) {
      return next(err);
    }
    teams.forEach(function(t) {  t.remove(); });
    next();
  });
});

Team 模型应以名称 Team 导出。喜欢:

module.exports = mongoose.model('Team', TeamSchema);

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 2018-03-03
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多