Mongoose不会将嵌套的Object保存在另一个嵌套的Object中

时间:2014-06-20 13:09:11

标签: node.js mongodb mongoose save nested

通常在mongoose中保存对象嵌套,通过父亲的调用方法保存,但如果我们有两个级别的订婚,祖父,父亲[嵌套],儿子[嵌套],儿子不通过父亲的通话方法保存保存

祖父 - >小组

var schema = new mongoose.Schema({
   name: String,
   days:[mongoose.Schema.Types.Day],
});

module.exports = mongoose.model('Group', schema);

父亲 - >天

var schema = new mongoose.Schema({
   _id: Number,
   matches:[mongoose.Schema.Types.Match]
});
module.exports = mongoose.model('Day', schema);

儿子 - >匹配

var schema = new mongoose.Schema({
  team1: {
    type: Schema.ObjectId,
    ref:'Team'
  },
  team2: {
    type: Schema.ObjectId,
    ref: 'Team'
  },
  score: [Number]
});

module.exports = mongoose.model('Match', schema);

在路线(“matches.js”)中,我尝试联合保存该组并进行匹配。

Group.findById(groupId).exec(
        function(err, group){
        var match = new Match();
        var day = group.days[dayNumber-1];
        day.matches.push(
            match
        );
        group.save(function(err){
            console.log("success");
            console.log("group in matches.js:"+group);
            res.redirect("/tournaments/"+tournamentId+"/groups/"+groupId+"/days/"+dayNumber);
        });
     });

在重定向中,我再次打印“组”并且匹配消失。

app.get('/tournaments/:tournamentId/groups/:groupId/days/:dayNumber', function (req, res) {
    groupId = req.params.groupId;
    dayNumber =  req.params.dayNumber;
    Group.findById(groupId, function (err, group) {
        console.log("group in days.js:"+group);
        res.render('days/show', {
            title: 'Days',
            group:  group,
            day:group.days[dayNumber-1],
            tournamentId: req.params.tournamentId
        });
    });
});

控制台日志打印:

new match
success
group in matches.js:{ __v: 7,
  _id: 53a3ee54dfe793bd9a20c6ab,
  name: 'gruppo sdirubbo',
  days: [ { matches: [Object], _id: 1 } ] }
GET /tournaments/539f0185ea17e46e73be937b/groups/53a3ee54dfe793bd9a20c6ab/days/1/newMatch 302 4ms - 208b
group in days.js:{ __v: 7,
  _id: 53a3ee54dfe793bd9a20c6ab,
  name: 'gruppo sdirubbo',
  days: [ { matches: [], _id: 1 } ] }

1 个答案:

答案 0 :(得分:1)

mongoose.Schema.Types.Daymongoose.Schema.Types.Match未定义,因此引用它们的那些数组字段最终会以Mixed类型结束而不会保存,除非您明确标记它们已修改。

您需要在模型定义之间使用这些模式,然后在定义中使用这些模式。例如:

var matchSchema = new mongoose.Schema({
  team1: {
    type: Schema.ObjectId,
    ref:'Team'
  },
  team2: {
    type: Schema.ObjectId,
    ref: 'Team'
  },
  score: [Number]
});

var daySchema = new mongoose.Schema({
   _id: Number,
   matches:[matchSchema]
});

var groupSchema = new mongoose.Schema({
   name: String,
   days:[daySchema],
});