简体   繁体   中英

Remove embedded document in mongoose

I'm new to node.js and MongoDB. I'm using the Mongoose Library for accessing MongoDB with node.js.

I have two Schemas, Book and Author. Author belongs_to a Book and Book has_many Author.

I have this in my schemas:

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' );

The problem is that when I delete a document from Author which is embedded with Book it is deleted without checking the referential integrity. My scenario is that if the Author document is embedded with the Book it can't be deleted. Is Mongoose automatically check the author document embedded in the book ? Is it possible? then how?

You can try the following code for the schema you mentioned.

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

More info on SchemaObj.pre(method,callback)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM