2014년 12월 12일 금요일

[mongoose] Creating a model with no collection

I would like to have a child schema that is *only* used as a sub-schema within a parent.   They will never exist independently of the parent schema.  I would also like to be able to compile a model on that schema to get the benefits of Model, such as methods.   Is it considered "valid" to call mongoose.model() will null as the collection?  Is there a better way to do what I'm trying to do?

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/LearnBoost/mongoose/issues/2534


댓글 없음:

댓글 쓰기