500 error: Cast to ObjectId failed for value at path \"_id\" for Mongoose model using ResourceJS

500 error: Cast to ObjectId failed for value at path \"_id\" for Mongoose model using ResourceJS

按照 MEAN App repo, I get the following message, when I access the URL http://localhost:3000/movie/584c6f00cf996a9956784807:

中的说明逐步安装 resourcejs

{"status":500,"message":"Cast to ObjectId failed for value \"584dd2842a056e4a648751b5\" at path \"_id\" for model \"movie\"","errors":{}}

POST 请求也有效,但 PUT 和 DELETE 无效。

index.js

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var methodOverride = require('method-override');
var _ = require('lodash');

var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));

// CORS Support
app.use(function(req, res, next) { 
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

mongoose.connect('mongodb://localhost/meanapp');
mongoose.connection.once('open', function() {

  // Load the models.
  app.models = require('./models/index');

  var routes = require('./routes');
  var numberOfRoutes = 1;
  _.each(routes, function(controller, route) {
    app.use(route, controller(app, route));
  });

  app.listen(3000);
});

MovieController.js

var Resource = require('resourcejs');
module.exports = function(app, route) {

  // Setup the controller for REST;
  Resource(app, '', route, app.models.movie).rest();

  // Return middleware.
  return function(req, res, next) {
    next();
  };
};

电影模型看起来就像 this, and is being served this way

我的兴趣点是 ResourceJS 有以下代码,它似乎无法将 ID 正确解析为 MongoDB ObjectID :

/**
 * Register the GET method for this resource.
 */
get: function(options) {
    (…)
    var search = {'_id': req.params[this.name + 'Id']}; 
    (…)
}

这可能是什么问题?

统计数据 Windows 10 — 64 位 OS,基于 x64 的处理器 MongoDB v3.2.7,64 位 节点JS v4.4.7 猫鼬 v4.7.6

因为 mongoose 想要 ObjectId 但你将 string 作为 _id 传递,所以你应该对其进行类型转换。

试试这个:

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

/**
 * Register the GET method for this resource.
 */
get: function(options) {
    (…)
    var param = req.param[this.name + 'Id'];
    var search = {'_id': new ObjectId(param)}; 
    (…)
}

如果您需要适用于任何版本的 Mongoose 和 Mongo 的通用解决方案,只需将 _id 字段定义为字符串并使用 uuid.v4 生成唯一值:

var uuid = require('uuid');
var mongoose = require('mongoose');

// Create the MovieSchema.
var MovieSchema = new mongoose.Schema({
    _id: { 
      type: String, 
      index: { unique: true }, 
      default: uuid.v4 
    },
    title: {
       type: String,
       required: true
    },
    url: {
      type: String,
      required: true
    }
 });

 // Export the model.
 module.exports = mongoose.model('movie', MovieSchema);

所以在这种情况下,您的 ResourceJS 将保持原样并正常工作:

get: function(options) {
    (…)
    var search = {'_id': req.param[this.name + 'Id']}; 
    (…)
}

P.S。不要忘记安装 uuid 包:

npm i --save uuid