我为模式设置了一个中间件查询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
架构(顺便说一下,此查询中的 post 查询有效):
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
有人可以帮我吗?