首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB/猫鼬在两个模型之间建立关系?

MongoDB/猫鼬在两个模型之间建立关系?
EN

Stack Overflow用户
提问于 2015-08-09 03:43:08
回答 1查看 1.7K关注 0票数 1

我希望按照这个模式http://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/创建一对多的关系。

我有一个Exercise.js模式,它将包含一组练习。

代码语言:javascript
复制
var exerciseSchema = new mongoose.Schema({

  _id: String,
  title: String,
  description: String,
  video: String,
  sets: Number,
  reps: String, 
  rest: Number

});

然后我就有了一个锻炼计划BeginnerWorkout.js模式

代码语言:javascript
复制
var workoutDaySchema = new mongoose.Schema({

  _id: String,
  day: Number,
  type: String,
  exercises: Array

});

我想将一系列的练习与workoutDaySchema联系起来,这包含了一组特定锻炼的锻炼天数,每天都有一组练习。

我有一个播种机功能,为我产生锻炼。

代码语言:javascript
复制
check: function() {

    // builds exercises
    Exercise.find({}, function(err, exercises) {
        if(exercises.length === 0) {
            console.log('there are no beginner exercises, seeding...');
            var newExercise = new Exercise({
                _id: 'dumbbell_bench_press',
                title: 'Dumbbell Bench Press',
                description: 'null',
                video: 'null',
                sets: 3, // needs to be a part of the workout day!!
                reps: '12,10,8', 
                rest: 1
            });
            newExercise.save(function(err, exercises) {
                console.log('successfully inserted new workout exercises: ' + exercises._id);
            });
        } else {
            console.log('found ' + exercises.length + ' existing beginner workout exercises!');
        }
    });


    // builds a beginner workout plan
    BeginnerWorkout.find({}, function(err, days) {
        if(days.length === 0) {
            console.log('there are no beginner workous, seeding...');
            var newDay = new BeginnerWorkout({
                day: 1,
                type: 'Full Body',
                exercises: ['dumbbell_bench_press'] // here I want to pass a collection of exercises.
            });
            newDay.save(function(err, day) {
                console.log('successfully inserted new workout day: ' + day._id);
            });
        } else {
            console.log('found ' + days.length + ' existing beginner workout days!');
        }
    });

}

因此,我的问题是在建立一个锻炼计划,我如何能够关联到exercises键使用猫鼬演习?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-09 07:01:07

试试这个:

代码语言:javascript
复制
exercises: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Exercise', required: false }]

并使用exercise._id将练习添加到锻炼中(在上面的代码中,您需要将其放在相关的回调中,例如练习中的.save回调):

代码语言:javascript
复制
newDay.exercises.push(newExercise._id);

_id通常是一个生成的数字,所以我不知道您是否可以将它设置为您建议的文本字符串。

当你进行.find()锻炼时,你也需要填充这些练习。类似于:

代码语言:javascript
复制
BeginnerWorkout.find({}).
    .populate('exercises')
    .exec(function(err, exercises) {
    //etc
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31900673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档