删除mongoose中embedded的文件

我是node.js和MongoDB的新手。 我正在使用Mongoose库通过node.js访问MongoDB。

我有两个模式,书和作者。 作者belongs_to书和书has_many作者。

我在我的模式中有这个:

var mongoose = require( 'mongoose' ); var Schema = mongoose.Schema; var Book = new Schema({ title : String, isbn : String, authorId : [{ type: Schema.Types.ObjectId, ref: 'Author' }], updated_at : Date }); var Author = new Schema({ name : String, updated_at : Date }); mongoose.model( 'Book', Book ); mongoose.model( 'Author', Author ); mongoose.connect( 'mongodb://localhost/library' ); 

问题是,当我从Book中embedded的作者中删除文档时,它将被删除而不检查参照完整性。 我的情况是,如果“作者”文档与“书籍”embedded,则无法删除。 Mongoose是否自动检查书中embedded的作者文档? 可能吗? 那么怎么样?

您可以为您提到的架构尝试以下代码。

 Author.pre('remove', function(next) { Author.remove({name: this.name, updated_at: this.updated_at }).exec(); Book.remove({authorId : this._id}).exec(); next(); }); 

有关SchemaObj.pre(方法,callback)的更多信息