【发布时间】: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