使用nodejs在mongoose模式中的数组中添加值

时间:2016-11-10 03:47:22

标签: node.js mongodb mongoose mongoose-populate

我正在开发一个在线课程申请表。我已经为课程注册创建了一个集合,我将存储课程名称和在该课程中注册的用户。 Mongoose模式看起来像这样。它的名字是courseEnrollment.js。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var courseEnrollment = new Schema({


courseEnrolled: [{courseName : String},
                 {username : [{user : String}]}
                ]

}, {collection : 'courseEnrollment'});

module.exports = mongoose.model('courseEnrollment', courseEnrollment);

当用户点击“注册”时,GET请求将转到“localhost:3000 / learn /:courseName / enroll”。 在该路由处理程序中,我将用户课程注册信息存储在两个不同的集合中。 1)在课程集中,我在上面展示了。 2)在存储用户名,密码等的用户帐户信息中,我还存储用户注册的课程。

现在我遇到的问题是,它只更新了User集合,而不是出于某种原因更新了courseEnrollment集合。它会出现以下错误。

events.js:141
  throw er; // Unhandled 'error' event
  ^

TypeError: Cannot read property 'push' of undefined
at /home/mobileedx/WebstormProjects/passportAuthentication/routes/index.js:387:47
at Query.<anonymous> (/home/mobileedx/WebstormProjects/passportAuthentication/node_modules/mongoose/lib/model.js:3340:16)
at /home/mobileedx/WebstormProjects/passportAuthentication/node_modules/mongoose/node_modules/kareem/index.js:259:21
at /home/mobileedx/WebstormProjects/passportAuthentication/node_modules/mongoose/node_modules/kareem/index.js:127:16
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)

这是我在“localhost:3000 / learn /:courseName / enroll”

的路由处理程序中的代码
  /**
  * Here If a user clicks on enroll, then the GET request will come on this page. If user is not authenticated then it
 * will redirect to the login page. If user is logged in then, user will get the courseHome page.
 */

 router.get('/learn/:courseName/enroll', isAuthenticated, function (req, res) {

  var user = req.user.username;
  var course = req.params.courseName;

  console.log('user trying to enroll is: ' + user);
  console.log('coursename user is trying to enroll is: ' + course);

  courseEnrollment.findOne({ 'courseEnrolled.courseName' :  req.params.courseName }, function(err, courseEnroll) {
      // In case of any error, return using the done method
      if (err) {
          console.log('Error in SignUp: ' + err);
          return done(err);
      }
      console.log('courseEnroll value is: ' + courseEnroll);

      courseEnroll.courseEnrolled.username.push({ "user": req.user.username});

      courseEnroll.save(function (err, data) {
          if (err)
              throw err;
          else {
              console.log('course Updated in courseEnrollment collection');
          }
      });
  });


  // When a user clicks on 'enroll' to enroll to a course, then the course name should be added in the
  // user's courseEnrolled list as well. This is what we are doing here.


  User.findOne({ 'username' :  req.user.username }, function(err, user) {
      // In case of any error, return using the done method
      if (err) {
          console.log('Error in SignUp: ' + err);
          return done(err);
      }
      console.log('user value is: ' + user);
      console.log('username value is: ' + user.username);
      user.courseEnrolled.push({ "courseName": course});

      user.save(function (err, data) {
          if (err)
              throw err;
          else {
              console.log('course Updated in user account collection');
          }
      });

      res.render('home', {user: req.user});
  });
});

请告诉我,我在这里出错了。我可以使用mongoose填充来填充courseEnrollment集合中用户集合的用户名字段中的用户名。如果是的话,那该怎么办呢。 感谢。

1 个答案:

答案 0 :(得分:1)

据我猜测,架构存在问题。你的课程注册模式。应该如下。每个课程包含一个对象的数组。其中包含有关其名称和注册的用户的信息。

   courseEnrolled: [{
           courseName : String,
           username : [{user : String}]
    }]

希望它有所帮助。

............................................... ..

好的,如果这只是维护加入特定课程的用户的模式。然后,您可以按照以下架构

var courseEnrollment = new Schema({
   courseName : String:,
   usersEnrolled : [String]
}, {collection : 'courseEnrollment'});

可以在这样的查询中访问它。

  courseEnrollment.findOne({ 'courseName' :  req.params.courseName }, function(err, courseEnroll) {
  // In case of any error, return using the done method
  if (err) {
      console.log('Error in SignUp: ' + err);
      return done(err);
  }
  console.log('courseEnroll value is: ' + courseEnroll);

  courseEnroll.username.push({ "user": req.user.username});

  courseEnroll.save(function (err, data) {
      if (err)
          throw err;
      else {
          console.log('course Updated in courseEnrollment collection');
      }
  });

});