6

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?

Jetson John
  • 3,759
  • 8
  • 39
  • 53
  • 1
    No, there isn't any referential integrity checking built in. However, you can add that via 'remove' middleware as in [this answer](http://stackoverflow.com/a/14349259/1259510). – JohnnyHK Apr 03 '13 at 12:30

1 Answers1

1

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)

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
  • in this way we donot need to write findOneAndDelete method in controller ? is my assumption are correct? – Mohammed Feb 03 '22 at 11:11