gpt4 book ai didi

node.js - Mongoose Middleware pre 'remove' 不起作用,Model.update 不是函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:18 26 4
gpt4 key购买 nike

我为 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

有人可以帮我吗?

最佳答案

我认为你应该使用 .pre() 代替。希望这样的事情对你有用:

bookSchema.pre('remove', function (next) {
var book = this;
book.model('User').update(
{ books: book._id },
{ $pull: { books: book._id } },
{ multi: true },
next);

});

关于node.js - Mongoose Middleware pre 'remove' 不起作用,Model.update 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com