简体   繁体   English

无法从node.js更新mongodb中的文档

[英]Not able to update document in mongodb from node.js

I am developing an online course application and I am trying to add new video lectures for a particular course, once the course is created. 我正在开发一个在线课程应用程序,我正在尝试在创建课程后为特定课程添加新的视频讲座。 Once a course is created, after that, if we try to add new course then it sends update request, even if I am adding new video lectures, which is not present so far in the MongoDB. 一旦创建了一个课程,之后,如果我们尝试添加新课程,那么它就会发送更新请求,即使我正在添加新的视频讲座,到目前为止在MongoDB中还没有。 Here is my mongoose schema. 这是我的猫鼬模式。 File Name:- course.server.model.js. 文件名: - course.server.model.js。

    'use strict';
 /**
  * Module dependencies
  */
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 /**
  * Course Schema
  */
 var CourseSchema = new Schema({
     created: {
         type: Date,
         default: Date.now
     },
     title: {
         type: String,
         default: '',
         trim: true,
         required: 'Title cannot be blank'
     },
     content: {
         type: String,
         default: '',
         trim: true
     },
     // courseLecture: [String],
     courseLecture: [{
         lecture_title: {
             type: String
         },
         //  week_number: { type: Number },
         lecture_video: [String],
         pdf_files: [String]
         // lecture_video: [{ videoUrl: String }]
     }],
     /*
     courseLecture: {
     type: String,
     default: '',
     trim: true
     },*/
     user: {
         type: Schema.ObjectId,
         ref: 'User'
     }
 });

 mongoose.model('Course', CourseSchema);

Here is my node.js controller which updates the course. 这是我的node.js控制器,它更新了课程。 File Name:- courses.server.controller.js 文件名: - courses.server.controller.js

   'use strict';

 /**
  * Module dependencies
  */
 var path = require('path'),
     mongoose = require('mongoose'),
     Course = mongoose.model('Course'),
     errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

 /**
  * Create an course
  */
 exports.create = function(req, res) {
     var course = new Course(req.body);
     course.user = req.user;

     course.save(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * Show the current course
  */
 exports.read = function(req, res) {
     // convert mongoose document to JSON
     var course = req.course ? req.course.toJSON() : {};

     // Add a custom field to the Course, for determining if the current User is the "owner".
     // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Course model.
     course.isCurrentUserOwner = !!(req.user && course.user && course.user._id.toString() === req.user._id.toString());

     console.log('course value is: ' + course);
     console.log('video lecture embed value is: ' + course.courseLecture.lecture_video);

     res.json(course);
 };

 /**
  * Update an course
  */
 exports.update = function(req, res) {
     var course = req.course;

     course.title = req.body.title;
     course.content = req.body.content;
     course.courseLecture.lecture_video = req.body.courseLecture.lecture_video;
     course.courseLecture.lecture_title = req.body.courseLecture.lecture_title;
     course.courseLecture.pdf_files = req.body.courseLecture.pdf_files;
     console.log('course lecture video url is: ' + req.body.courseLecture.lecture_video);
     course.save(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * Delete an course
  */
 exports.delete = function(req, res) {
     var course = req.course;

     course.remove(function(err) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(course);
         }
     });
 };

 /**
  * List of Courses
  */
 exports.list = function(req, res) {
     Course.find().sort('-created').populate('user', 'displayName').exec(function(err, courses) {
         if (err) {
             return res.status(422).send({
                 message: errorHandler.getErrorMessage(err)
             });
         } else {
             res.json(courses);
         }
     });
 };

 /**
  * Course middleware
  */
 exports.courseByID = function(req, res, next, id) {

     if (!mongoose.Types.ObjectId.isValid(id)) {
         return res.status(400).send({
             message: 'Course is invalid'
         });
     }

     Course.findById(id).populate('user', 'displayName').exec(function(err, course) {
         if (err) {
             return next(err);
         } else if (!course) {
             return res.status(404).send({
                 message: 'No course with that identifier has been found'
             });
         }
         req.course = course;
         next();
     });
 };

Interestingly I am able to update two fields ie title and content, however, whatever is there inside the courseLecture array, that I'm not able to update or make new save. 有趣的是,我能够更新两个字段,即标题和内容,但是,在courseLecture数组中,我无法更新或进行新的保存。 Please let me know, where I am going wrong here. 请让我知道,我在这里出错了。

TO add more clarity about my frontend work, I'm adding my angular controller and HTML file code. 为了增加关于我的前端工作的清晰度,我正在添加我的角度控制器和HTML文件代码。 Angular controller. 角度控制器。 File name :- course.client.controller.js 文件名: - course.client.controller.js

(function () {
'use strict';

angular
.module('courses.admin')
.controller('CoursesAdminController', CoursesAdminController);

CoursesAdminController.$inject = ['$scope', '$state', '$window', 'courseResolve', 'Authentication', 'Notification'];

function CoursesAdminController($scope, $state, $window, course, Authentication, Notification) {
var vm = this;

vm.course = course;
vm.authentication = Authentication;
vm.form = {};
vm.remove = remove;
vm.save = save;
vm.ShowHide = ShowHide;
vm.addNewChoice = addNewChoice;

$scope.IsVisible = false;
function ShowHide() {
  // If DIV is visible it will be hidden and vice versa.
  $scope.IsVisible = $scope.IsVisible ? false : true;
}

function addNewChoice() {
  $scope.vm.course.courseLecture.push('');
}

// Remove existing Course
function remove() {
  if ($window.confirm('Are you sure you want to delete?')) {
    vm.course.$remove(function() {
      $state.go('admin.courses.list');
      Notification.success({ message: '<i class="glyphicon glyphicon-ok"></i> Course deleted successfully!' });
    });
  }
}

// Save Course
function save(isValid) {
  if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'vm.form.courseForm');
    return false;
  }

  // Create a new course, or update the current instance
  vm.course.createOrUpdate()
    .then(successCallback)
    .catch(errorCallback);

  function successCallback(res) {
    $state.go('admin.courses.list'); // should we send the User to the list or the updated Course's view?
    Notification.success({ message: '<i class="glyphicon glyphicon-ok"></i> Course saved successfully!' });
  }

  function errorCallback(res) {
    Notification.error({ message: res.data.message, title: '<i class="glyphicon glyphicon-remove"></i> Course save error!' });
  }
}
}
}());

My HTML file. 我的HTML文件。 File Name:- form-course.client.view.html 文件名: - form-course.client.view.html

<section>
<div class="page-header">
  <h1>{{vm.course._id ? 'Edit Course' : 'New Course'}}</h1>
</div>
<div class="pull-right">
  <a ng-show="vm.course._id" class="btn btn-primary" ng-click="vm.remove()">
  <i class="glyphicon glyphicon-trash"></i>
  </a>
 </div>
 <div class="col-md-12">
  <form name="vm.form.courseForm" class="form-horizontal" ng-submit="vm.save(vm.form.courseForm.$valid)" novalidate>
     <fieldset>
        <div class="form-group" show-errors>
           <label class="control-label" for="title">Title</label>
           <input name="title" type="text" ng-model="vm.course.title" id="title" class="form-control" placeholder="Title" required autofocus>
           <div ng-messages="vm.form.courseForm.title.$error" role="alert">
              <p class="help-block error-text" ng-message="required">Course title is required.</p>
           </div>
        </div>
        <div class="form-group">
           <label class="control-label" for="content">Content</label>
           <textarea name="content" data-ng-model="vm.course.content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>
        </div>
        <!--  <a class="btn btn-primary pull-right" data-ui-sref="admin.courses.createLecture">  -->
        <div>
           <a class="btn btn-primary pull-right" ng-click="vm.ShowHide()">
           <i class="glyphicon glyphicon-plus"></i>
           </a><br>
           <div ng-show="IsVisible">
              <div class="page-header">
                 <h1>{{vm.course._id ? 'Edit Lecture' : 'New Lecture'}}</h1>
              </div>
              <div class="pull-right">
                 <a ng-show="vm.course._id" class="btn btn-primary" ng-click="vm.remove()">
                 <i class="glyphicon glyphicon-trash"></i>
                 </a>
              </div>
              <div class="col-md-12">
  <form name="vm.form.courseForm" class="form-horizontal" ng-submit="vm.save(vm.form.courseForm.$valid)" novalidate>
  <fieldset data-ng-repeat="field in vm.course.courseLecture track by $index">
  <div class="form-group" show-errors>
  <label class="control-label" for="LectureTitle">Lecture Title</label>
  <input name="courseLecture" type="text" ng-model="vm.course.courseLecture.lecture_title[$index]" id="LectureTitle" class="form-control" placeholder="Lecture Title" required autofocus>
  <div ng-messages="vm.form.courseForm.title.$error" role="alert">
  <p class="help-block error-text" ng-message="required">Lecture name is required.</p>
  </div>
  </div>
  <div class="form-group">
  <label class="control-label" for="courseLecture">Add Lecture video url here</label>
  <input name="courseLecture" type="text" ng-model="vm.course.courseLecture.lecture_video[$index]" id="courseLecture" class="form-control" placeholder="course Lecture">
  </div>
  </fieldset>
  <input type="button" class="btn btn-default" ng-click="vm.addNewChoice()" value="Add another URL">
  </form>
  </div>
  </div>
  </div>
  <div class="form-group">
  <button type="submit" class="btn btn-default">{{vm.course._id ? 'Update' : 'Create'}}</button>
  </div>
  </fieldset>
  </form>
 </div>
</section>
 exports.update = function(req, res) {
 var course = req.course;

Your req.course is not a mongodb object. 你的req.course不是一个mongodb对象。 you can use findOneAndUpdate method of mongoose http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate 你可以使用mongoose的findOneAndUpdate方法http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

If your data currently looks like: 如果您的数据目前如下:

{
   courseLecture: {
     lecture_title: 'Test',
     lecture_video: ['vid1', 'vid2'],
     pdf_files: ['pdf1', 'pdf2']
   }
}

I think what you need to do is change this bit: 我想你需要做的就是改变这一点:

 courseLecture: [{
     lecture_title: {
         type: String
     },
     //  week_number: { type: Number },
     lecture_video: [String],
     pdf_files: [String]
     // lecture_video: [{ videoUrl: String }]
 }]

to this: 对此:

 courseLecture: {
     lecture_title: {
         type: String
     },
     lecture_video: {type: [String] },
     pdf_files: {type: [String] }
 }

You've initially defined the Schema as having an array of objects in the 'courseLecture' field, so either the validation doesn't pass during save, or the Schema doesn't even perform the set operation. 您最初在“courseLecture”字段中将Schema定义为具有对象数组,因此在保存期间验证不会通过,或者Schema甚至不执行set操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM