在mongodb中通过_id删除不起作用

时间:2016-05-23 08:38:49

标签: javascript angularjs node.js mongodb mean

我原本以为创建一个与我的mongodb一起使用的删除功能非常简单但是无法让它工作并且无法在google或SO上找到解决方案。

我正在使用使用用户和课程的MEAN堆栈创建应用程序,并使用示例来执行用户处理部分,因此删除功能适用于用户。当我试图复制它以便课程也有一个我无法让它工作。

已附加我用于创建服务的所有(相关)代码。其中一些可能不需要解决问题,并且与应用程序中的信息通信方式有关。如果需要其他任何内容,请与我们联系。

客户端代码

系统管理员/ index.controller

 function deleteCourse() {
    // CourseService calls app-services/course.service to enable 
   // all sub-pages to call all course-functions. 
    CourseService.Delete(event.target.id)
        .then(function(){
             initController();
            })
        .catch(function(error){
            });

    }

应用的服务/ course.service

function Delete(_id) {
    return $http.delete('/api/courses/' + _id).then(handleSuccess, handleError);
    }

服务器端代码

server.js

app.use('/api/courses', require('./controllers/api/courses.controller.js'));

我认为错误发生在以下文件中,或者在services / course.service.js中,这些错误在下面进一步说明。

courses.controller.js

var config = require('config.json');
var express = require('express');
var router = express.Router();
var CourseService = require('services/course.service');

router.delete('/:_id', deleteCourse);

module.exports = router;


function deleteCourse(req,res) {
//Do not now why req.user.sub works ( it passes on the ID). 
//Copied it from the corresponding function for User with the intention to change it to req.course.sub but that didn't work. 
//Somehow req.user.sub did to let it stay. Might cause the error? 

var courseID = req.user.sub;
CourseService.delete(courseID)
   .then(function(){
       res.sendStatus(200);
   })
   .catch(function (err) {
       res.status(400).send(err);
   });
}

服务/ course.service.js

var config = require('config.json');
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var Q = require('q');
var mongo = require('mongoskin');


//Connectionsstring to the mongo database, if the app is runed on openshift the connectionstring value will change.
var connectionString = "mongodb://localhost:27017/mean-stack-registration-login-example";
if(process.env.OPENSHIFT_MONGODB_DB_URL){
    connectionString = process.env.OPENSHIFT_MONGODB_DB_URL + "studycontrol";
}
var db = mongo.db(connectionString, { native_parser: true });

db.bind('courses');

var service = {};
service.delete = _delete;
module.exports = service;

// this is where I think the error occurs. this is the current version of it,       will include examples of what i've tried earlier below. Current version corresponds with the function for deleting users. 

function _delete(_id){
    var deferred = Q.defer();
    db.courses.remove(
        { _id: mongo.helper.toObjectID(_id) },
        function (err) {
            if (err) deferred.reject(err);

            deferred.resolve();
        });
    return deferred.promise;
}

我在上面的删除功能中尝试过的示例

// function(err) has been pretty much the same as for the delete function above for all tries. 

db.collection('courses').remove({"_id": ObjectID(_id)}, function(err)...)

db.courses.remove({"_id": "ObjectId"(_id)}, function (err)... )

db.courses.remove({"_id": "$oid":(_id)}, function(err)... )

same as above but without " " around _id, ObjectID and $oid

为services / user.service.js中的用户删除功能以进行比较

var config = require('config.json');
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var Q = require('q');
var mongo = require('mongoskin');


//Connects to the database with diffrent connectionstring based on if you connect localy or in openshift
var connectionString = "mongodb://localhost:27017/mean-stack-registration-login-example";
if(process.env.OPENSHIFT_MONGODB_DB_URL){
    connectionString = process.env.OPENSHIFT_MONGODB_DB_URL + "studycontrol";
}
var db = mongo.db(connectionString, { native_parser: true });

db.bind('users');

var service = {};
service.delete = _delete;
module.exports = service;

//Deletes the user form the database based on ID.
function _delete(_id) {
    var deferred = Q.defer();

    db.users.remove(
        { _id: mongo.helper.toObjectID(_id) },
       function (err) {
            if (err) deferred.reject(err);
            deferred.resolve();
        });
    return deferred.promise;
}

编辑一直在尝试Sundar和anwerjunaid的建议,并决定使用一些console.log来试图弄清楚发生了什么。

下面是我尝试过的一个例子和我得到的日志

db.courses.remove(
        { "_id": _id},
        function (err) {
            if (err) deferred.reject(err);
            deferred.resolve();
            console.log('inside')
            console.log(deferred);
        });
   console.log('outside')
   console.log(deferred)
   return deferred.promise;


outside
defer {
    promise: { state: 'pending' },
    resolve: [Function],
    fulfill: [Function],
    reject: [Function],
    notify: [Function] }
inside
defer {
  promise: { state: 'fulfilled', value: undefined },
  resolve: [Function],
  fulfill: [Function],
  reject: [Function],
  notify: [Function] }

这是否意味着它在db.courses.remove完成之前执行return.deferred.promise?这可能是导致错误的原因吗?

2 个答案:

答案 0 :(得分:0)

您也可以尝试使用ObjectId类型:

var ObjectId = require('mongoose').Types.ObjectId;
var query = { _id: new ObjectId(id) }; // Pass string Id here

现在使用删除此处查询

db.collection('courses').remove(query, function(err, result){
     //
})

答案 1 :(得分:0)

我解决了,错误来自courses.controller.js中的以下行

var courseID = req.user.sub;

愚蠢的错误,它将courseID设置为当前用户的ID,因此它尝试删除具有不存在的ID的课程。

解决方案如下所示:

<强> courses.controller.js

function deleteCourse(req,res) {
    var courseID = req.params._id;

   CourseService.delete(courseID)
       .then(function(){
           res.sendStatus(200);
       })
       .catch(function (err) {
           res.status(400).send(err);
       });
}

<强>服务/ course.service.js

function _delete(_id) {                                   
    var deferred = Q.defer();                             

    db.courses.remove(                                    
        { _id: mongo.helper.toObjectID(_id) },            
        function (err) {                                  
            if (err) deferred.reject(err);                                                          
            deferred.resolve();                           
        });                                               
    return deferred.promise;                              
}