Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
Jetson John Avatar asked Apr 03 '13 07:04

Jetson John


1 Answers

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)

like image 194
Amol M Kulkarni Avatar answered Oct 04 '22 03:10

Amol M Kulkarni