允许用户将项目添加到其配置文件Mongoose

时间:2015-10-15 10:33:01

标签: angularjs node.js mongodb mean

我正在使用express和mongoose构建一个平均堆栈应用程序。我有两个模式,userSchema和courseSchema:

 var mongoose = require('mongoose'),
          Schema = mongoose.Schema;    
    var courseSchema = mongoose.Schema({
      title:{type:String, required:'{PATH} is required!'},
      featured:{type:Boolean, required:'{PATH} is required!'},
      published:{type:Date, required:'{PATH} is required!'},
      courseLink:{type:String, required:'{PATH} is required!'},
      user: [{type:Schema.Types.ObjectId, ref : 'User'}]

    });

var Course = mongoose.model('Course', courseSchema);

module.exports = Course;

var userSchema = mongoose.Schema({
        firstName: {type: String, required: true},
        lastName: {type: String, required: true},
        username: {
                    type: String,
                    required: true,
                    unique: true    // creates unique index inside MongoDB          
        },
        salt: {type: String, required: true},
        hashed_pwd: {type: String, required: true},
        roles:[String],
        courses:[{type: Schema.ObjectId, 
                 ref: 'Course' }]
    });

我能够创建用户和课程(作为管理员)。我现在要做的是允许每个用户在他的课程列表中添加课程(或者只需点击课程旁边的“喜欢”按钮,该课程就会添加到他的个人资料中)。

在控制器一侧,我试图从会话中检查用户ID,找到该用户并将该课程添加到他的文档中。但那就是我被困住的地方,

exports.addMyCourse = function(req, res){
  console.log('user id', req.session.passport.user);
  console.log('id', req.body._id);
    var currentUserId = req.session.passport.user;

    User.findOne({'_id':currentUserId}, function(err, doc){
        console.log(doc);
  });

我看到的大部分解决方案都不是很明确。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

解决:

我使用$ addToSet将课程对象添加到User模型中的courses数组中:

这可能对搜索类似信息的人有用:

我的用户架构:

var userSchema = mongoose.Schema({

        firstName: {type: String, required: true},
        lastName: {type: String, required: true},
        username: {
                    type: String,
                    required: true,
                    unique: true    // creates unique index inside MongoDB          
        },
        salt: {type: String, required: true},
        hashed_pwd: {type: String, required: true},
        roles:[String],
        courses:[{
            type:Schema.ObjectId, ref:'Course'
        }]
    });
var User = mongoose.model('User', userSchema);

我的课程架构:     var mongoose = require(' mongoose'),           Schema = mongoose.Schema;

var courseSchema = mongoose.Schema({
  title:{type:String, required:'{PATH} is required!'},
  featured:{type:Boolean, required:'{PATH} is required!'},
  published:{type:Date, required:'{PATH} is required!'},
  courseLink:{type:String, required:'{PATH} is required!'}
});    

var Course = mongoose.model('Course', courseSchema);

在我的控制器文件夹中,我有users.js和courses.js:

在courses.js文件中,我创建了addMyCourses中间件来更新User模型的课程数组,首先从会话中检索当前用户的id并使用$ addToSet插入对象并避免同时重复。此外,我确保我只添加了课程的ObjectId,而不是整个课程文档,所以我在一个文档中没有太多数据的未来问题:

exports.addMyCourse = function(req, res){
  var myCourse = {
        title: req.body.title,
        featured: req.body.featured,
        published: req.body.published,
        courseLink: req.body.courseLink
  };

  var currentUserId = req.session.passport.user;   

  var courseId = req.body._id;

  User.update({_id:currentUserId},
        {$addToSet: {"courses": courseId}},
        {safe: true, upsert: true, new : true},
        function(err, model) {
            console.log(model);
        }
    );
};

由于我只有User模型的课程数组中的课程的ObjectId,我不得不使用mongoose的populate()方法对两个模型进行联合查询,以便我得到ids的相应课程文件。

在users.js文件中:

exports.getUserCourses = function(req, res, next){
      var currentUserId = req.session.passport.user; 
  User.findById(currentUserId).populate('courses')
    .exec(function(err, data){
      if(err) {
        console.log(err);
      } 
      console.log('user courses', data);
      res.send(data);
    })
  };