我有两个不同的模型User和Leave,我想设置它,这样每当删除一个假,那么该离开也将从用户文档中的一系列叶子中拉出。
用户模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const muv = require('mongoose-unique-validator');
const Leave = require('./leave');
const { ObjectID } = require('mongodb');
var schema = new Schema({
fullName: {
type: String,
required: true,
unique: true
},
leaveCredits: {
type: Number
},
filedLeaves: [{
type: Schema.Types.ObjectId,
ref: 'Leave'
}]
}, {
usePushEach: true
});
schema.plugin(muv);
schema.pre('remove', function (next) {
let user = this;
let toDelete = [];
user.filedLeaves.forEach(function(item) {
Leave.findByIdAndRemove(new ObjectID(item), (err, succ) => {
if (succ) {
console.log(`${item} Deleted`);
}
});
});
next();
});
module.exports = mongoose.model('User', schema);
离开模特:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = require('../models/user');
const { ObjectID } = require('mongodb');
var schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
status: {
type: String,
required: true
},
start: {
type: String,
required: true
},
end: {
type: String,
required: true
},
type: {
type: String,
required: true
}
});
// makes sure that the removed date is also removed from the User's leave array
schema.pre('remove', function (next) {
let leave = this;
User.findById(new ObjectID(leave.userId), function (err, user) {
user.filedLeaves.pull(leave._id);
user.save();
});
next();
});
module.exports = mongoose.model('Leave', schema);
它一直给我一个错误User.findById is not a function
,但我很确定我已经将它们正确地导出为模型,因为我的整个应用程序除了我现在遇到的这个小问题之外还有效。
尝试使用Google搜索,但我看到的所有内容都没有帮我解决这个问题。
修改 尝试使用find(),但仍然抛出相同的错误,它不是一个函数。
答案 0 :(得分:1)
您遇到的问题是您的架构需要另一个架构才能工作。这是一个循环要求问题。
要使其正常工作,您可以使用以下修复:
// makes sure that the removed date is also removed from the User's leave array
schema.pre('remove', function (next) {
const User = require('../models/user');
let leave = this;
User.findById(new ObjectID(leave.userId), function (err, user) {
user.filedLeaves.pull(leave._id);
user.save();
});
next();
});
schema.pre('remove', function (next) {
const Leave = require('./leave');
let user = this;
let toDelete = [];
user.filedLeaves.forEach(function(item) {
Leave.findByIdAndRemove(new ObjectID(item), (err, succ) => {
if (succ) {
console.log(`${item} Deleted`);
}
});
});
next();
});
我们只在pre
被调用时才提出要求。这避免了循环问题。