我为Book
架构设置了中间件查询:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User= require('./user');
var schema = new Schema({
name : {type: String, required:true},
startDate: {type: Date},// UTC datetime
endDate: {type: Date},// UTC datetime
status: {type: String},
user: {type: Schema.Types.ObjectId, ref: 'User'}
});
schema.post('remove', function(next) {
User.update(
{ books: this._id},
{ $pull: { books: this._id } })
.exec();
next();
});
module.exports = mongoose.model('Book', schema);
正如您所看到的那样,它会尝试从用户的图书清单中删除该图书。有关参考,请参阅User
架构(此处的帖子查询顺便说一下):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Book = require('./book');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String},
phone1: {type: String},
phone2: {type: String},
email: {type: String},
address: {type: Schema.Types.ObjectId, ref: 'Address'},
books: [{type: Schema.Types.ObjectId, ref:'Book'}]
});
schema.post('remove', function (user) {
Book.findById({$in : user.books}, function (err, book) {
if (err) {
return res.status(500).json({
title: 'An error occurred cascade delete operations for user',
error: err
});
}
if (book) {
book.user= undefined;
book.save();
}
});
});
module.exports = mongoose.model('User', schema);
我继续收到此错误,我在查询中尝试了多种变体,但无济于事:
process.nextTick(function() { throw err; });
TypeError: User.update is not a function
有人可以帮帮我吗?
答案 0 :(得分:2)
由于使用 require()将每个模型导入另一个模型,这可能会导致循环依赖。
尝试替换使用 require()来导入模型:
var User = require('./user')
...和
var Book = require('./book')
相反,在需要使用它的时候从mongoose获取模型,例如:
mongoose.model('User').update(...)
...和
mongoose.model('Book').findById(...)
另请注意,您可能需要在计划使用它们的文件中使用 require()导入这两个模块,以便在使用之前使用mongoose注册这两个模型。
我希望这会有所帮助。
答案 1 :(得分:1)
我认为你应该使用.pre()。希望这样的事情对你有用:
bookSchema.pre('remove', function (next) {
var book = this;
book.model('User').update(
{ books: book._id },
{ $pull: { books: book._id } },
{ multi: true },
next);
});