Mabrosche
Mabrosche

Reputation: 23

Unexpected behavior with Mongoose

Unexpected behavior

I have some model:

//test.js
var mongoose = require('../utils/mongoose');
var schema1 = new mongoose.Schema({
name: String
})

var schema2 = new mongoose.Schema({
objectsArray: [schema1]
});

schema1.pre('validate', function(next) {
console.log('pre validate schema1');
next();
});

module.exports = mongoose.model('Schema2', schema2);

Do save:

var o = new require('test')({ objectsArray: [{ name: 'Alex' }] });
o.save(function(err){
console.log('saved');
});

After, in console i get:

pre validate schema1
pre validate schema1
saved

The question is, Why? schema1.pre('validate')- appears 2 times, but i expect 1 time?

Upvotes: 0

Views: 375

Answers (1)

Mabrosche
Mabrosche

Reputation: 23

I find, answer on my question (thx to Aaron Heckmann)

add the pre hook to the child schema before passing it to the parent.

schema1.pre(..)
schema2 = Schema({ array: schema1 })

Upvotes: 2

Related Questions