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

时间:2017-02-04 17:35:14

标签: javascript angularjs node.js mongodb rest

我正在开发一个在线课程应用程序,我正在尝试在创建课程后为特定课程添加新的视频讲座。一旦创建了一个课程,之后,如果我们尝试添加新课程,那么它就会发送更新请求,即使我正在添加新的视频讲座,到目前为止在MongoDB中还没有。这是我的猫鼬模式。文件名: - course.server.model.js。

02/05 01:32:48: Launching app
No apk changes detected since last installation, skipping installation of C:\Users\Emily\AndroidStudioProjects\SST1\app\build\outputs\apk\app-debug.apk
$ adb shell am force-stop sst1.emily.example.com.sst1
$ adb shell am start -n "sst1.emily.example.com.sst1/sst1.emily.example.com.sst1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to sst1.emily.example.com.sst1
I/System.out: Sending WAIT chunk
W/ActivityThread: Application sst1.emily.example.com.sst1 is waiting for the debugger on port 8100...
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1493)
I/InstantRun: Instant Run Runtime started. Android package is sst1.emily.example.com.sst1, real application class is null.
W/InstantRun: No instant run dex files added to classpath
W/dalvikvm: VFY: unable to resolve interface method 15998: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
W/dalvikvm: VFY: unable to resolve interface method 16000: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
W/dalvikvm: VFY: unable to resolve interface method 16004: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
W/dalvikvm: VFY: unable to resolve virtual method 686: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
W/dalvikvm: VFY: unable to resolve virtual method 708: Landroid/content/res/TypedArray;.getType (I)I
W/dalvikvm: VFY: unable to resolve virtual method 16431: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
W/dalvikvm: VFY: unable to resolve virtual method 419: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
W/dalvikvm: VFY: unable to resolve virtual method 649: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
W/dalvikvm: VFY: unable to resolve virtual method 651: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
W/dalvikvm: VFY: unable to resolve instanceof 148 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416abe18)
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: sst1.emily.example.com.sst1, PID: 15643
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{sst1.emily.example.com.sst1/sst1.emily.example.com.sst1.MainActivity}: java.lang.IllegalArgumentException: you must specify a way to create the tab content
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
                      at android.app.ActivityThread.access$800(ActivityThread.java:156)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:157)
                      at android.app.ActivityThread.main(ActivityThread.java:5872)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.IllegalArgumentException: you must specify a way to create the tab content
                      at android.widget.TabHost.addTab(TabHost.java:225)
                      at sst1.emily.example.com.sst1.MainActivity.onCreate(MainActivity.java:22)
                      at android.app.Activity.performCreate(Activity.java:5312)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:156) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:157) 
                      at android.app.ActivityThread.main(ActivityThread.java:5872) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:515) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) 
                      at dalvik.system.NativeStart.main(Native Method) 

这是我更新课程的node.js控制器。文件名: - courses.server.controller.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);

有趣的是,我能够更新两个字段,即标题和内容,但是,无论课程数组中有什么内容,我都无法更新或进行新的保存。 请告诉我,我在这里出错了。

为了更清晰地说明我的前端工作,我添加了角度控制器和HTML文件代码。 角度控制器。文件名: - course.client.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();
     });
 };

我的HTML文件。文件名: - form-course.client.view.html

(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!' });
  }
}
}
}());

2 个答案:

答案 0 :(得分:0)

 exports.update = function(req, res) {
 var course = req.course;

您的req.course不是mongodb对象。你可以使用mongoose的findOneAndUpdate方法 http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

答案 1 :(得分:0)

如果您的数据目前如下:

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

我认为你需要做的就是改变这一点:

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

到此:

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

您最初将Schema定义为在&#39; courseLecture&#39;中有一系列对象。字段,因此要么验证在保存期间没有通过,要么架构甚至不执行set操作。