子アイテムの保存前フックで操作しようとしましたが、起動しないようです。マスターのプリセーブフックだけが発射されます。
Javascriptの私のモデル
var mongoose = require('mongoose');
mongoose.connect("localhost","test_master_details");
var masterSchema = mongoose.Schema({
title:{type:String,required:true},
childs: [childSchema]
});
masterSchema.pre('save',function(next){
console.log("master pre save called!");
console.log(this);
next();
});
var childSchema = mongoose.Schema({
number:{type:Number},
name: {type:String,required:true}
});
childSchema.pre('save',function(next){
this.number = 1;
//set number with the total number of childs for the parent master
console.log('child pre save called!');
console.log(this);
next();
});
module.exports = [mongoose.model('Child',childSchema), mongoose.model('Master',masterSchema)];
私のコーヒースクリプトの仕様:
model_container = require('../models/master')
Master = model_container[1]
Child = model_container[0]
should = require('should')
describe "Master model",->
before (done) ->
Master.remove {},(err) ->
console.log err if err
done()
it "should be able to create an instance",(done)->
master = new Master {title:"Master of command"}
master.save (err) ->
console.log err if err
should.exist master
done()
it "should be able to add 1 child", (done)->
master= new Master {title:"Master of command"}
master.childs.push {name:"hello world"}
master.save (err) ->
console.log err if err
master.childs.length.should.eql 1
done()
it "should be able to add 1 child with create method",(done) ->
master = new Master {title:"Master of command"}
child = new Child {name:"childs name"}
master.childs.push child
master.save (err) ->
console.log err if err
master.childs.length.should.eql 1
done()
子の事前保存が呼び出されない私のスペック結果は次のとおりです。
Master model
◦ should be able to create an instance: master pre save called!
{ title: 'Master of command',
_id: 50322715672b424e11000001,
childs: [] }
✓ should be able to create an instance
◦ should be able to add 1 child: master pre save called!
{ title: 'Master of command',
_id: 50322715672b424e11000002,
childs: [ { name: 'hello world' } ] }
✓ should be able to add 1 child
◦ should be able to add 1 child with create method: master pre save called!
{ title: 'Master of command',
_id: 50322715672b424e11000003,
childs: [ { name: 'childs name', _id: 50322715672b424e11000004 } ] }
✓ should be able to add 1 child with create method
✔ 3 tests complete (20ms)
私は何かが足りないのですか?私の理解では、コレクションに子供を追加して後で保存するときはいつでも、子供は事前に火を保存する必要があります。私は何を間違えますか?マスターコレクションに子を追加し、マスター値に基づいて値を事前設定できますか?
助けてくれてありがとう...