Here is some code to demonstrate what I'm talking about:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ChildSchema = new Schema({
name : String,
});
ChildSchema.methods.hello = function () {
console.log('Hi my name is ' + this.name);
};
ChildSchema.pre('save', function (next) {
console.log('save middleware called for ' + this.name);
next();
});
// collection set to null because we will NEVER be saving
// Child objects. They only exist within parent documents.
var Child = mongoose.model('Child', ChildSchema, null);
var ParentSchema = new Schema({
title : String,
children : [ ChildSchema ],
});
// collection is implicitly 'parents'
var Parent = mongoose.model('Parent', ParentSchema);
var c = new Child( { name : 'Bobby'} );
// output:
// Hi my name is Bobby
c.hello();
var p = new Parent({
title : 'I am the parent',
children : [ c ],
});
// output:
// save middleware called for Bobby
p.save();
Calling mongoose.model with collection=null is valid, but won't give you the result you expect. Mongoose will treat that as if you didn't pass a collection name at all, and thus just use the implicit collection name. Right now there unfortunately isn't a good way to do what you're trying to do without setting some collection name for the model, but this is definitely something worth considering for v4.0.
I think this is the same issue I am having, which I posted here https://github.com/
댓글 없음:
댓글 쓰기