无法通过Express路线从Mongodb删除文档

时间:2016-04-06 21:10:24

标签: javascript node.js express mongoose mongoose-schema

我想通过id删除Mongodb文档,将其传递给Express路由。
在控制台中,我收到一条消息,说明已将其删除。

GET /api/videolinks 304 94.792 ms - -
Removed id= 562b905f633288ac0d8b4567
DELETE /api/videolinks/562b905f633288ac0d8b4567 200 68.550 ms - 19743

但事实并非如此。

> db.hyperlinks.find({"_id": ObjectId("562b905f633288ac0d8b4567")})
{ "_id" : ObjectId("562b905f633288ac0d8b4567"), "file" : "http://storage.akamai.com/get/b113/p/coub/simple/cw_file/79632d71313/9aedca2cd4d3094e75834/iphone_hellosergii_iphone.mp4" }

我的Angularjs工厂:

/*global angular*/
angular.module('myService', [])

    // each function returns a promise object 
    .factory('Videolinks', ['$http',function($http) {
        return {
            get : function() {
                return $http.get('/api/videolinks');
            },
            delete : function(id) {
                return $http.delete('/api/videolinks/' + id);
            }
        };
    }]);

我的路线.js

var path = require('path');
var Videolink = require('./models/mydb');

var mongodb = require('mongodb');

// Get links
function getLinks(res){
  Videolink.find(function(err, hyperlinks) {
    // if there is an error retrieving, send the error. nothing after res.send(err) will execute
    if (err) {
        res.send(err);
    }

    res.json(hyperlinks); // return all videos in JSON format
  });
}

module.exports = function(app) {

    // api ---------------------------------------------------------------------

  // use mongoose to get all videos in the database
    app.get('/api/videolinks', function(req, res) {
        getLinks(res);
    });

    // delete a video
    app.delete('/api/videolinks/:video_id', function(req, res) {
        Videolink.remove({
            _id : mongodb.ObjectID(req.params.video_id)
        }, function(err) {

            if (err) {
                res.send(err);
            }
            console.log("Removed id= " + req.params.video_id);

            getLinks(res);
        });
    });


    // application -------------------------------------------------------------
    app.get('*', function(res) {
        res.sendFile('index.html', {root: path.join(__dirname, './public')}); // load the single view file 
    });
};

app.get功能在这里运作良好 app.delete会出现什么问题?

以下是models/mydb

中的数据库架构
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var db_schema = new Schema({
  //text: String
  _id: String,
  source: String,
  orig_page: String,
  likes: Number,
  title: String,
  file: String,
  video_mobile_res: String,
  video_high_res_mutes_muted: String,
  audio_high_res: String,
  video_med_res_muted: String,
  audio_med_res: String
}, {collection: 'hyperlinks'});

module.exports = mongoose.model('Videolink', db_schema);

1 个答案:

答案 0 :(得分:2)

您的特定问题是您在架构中将_id字段定义为字符串:

var db_schema = new Schema({
   _id: String,
   ...

拿出来,你的代码应该可以正常工作。您甚至可能发现了一个猫鼬错误,因为您应该能够指定_id字段类型。也许一些猫鼬专家可以告诉我们更多。