我甚至不确定这里的问题是什么,我一直想弄清楚几天。我对MEAN堆栈有些新意,所以我可能会遗漏一些明显的东西。我基本上复制了mean.io后端控制器,模型和路由以及Angular控制器,视图和服务的样板代码。当我通过浏览器创建新客户端时,我现在收到此错误:
CastError: Cast to ObjectId failed for value "undefined" at path "_id"
at ObjectId.cast (/Users/d/Web/personal/mean-app/node_modules/mongoose/lib/schema/objectid.js:116:13)
at ObjectId.castForQuery (/Users/d/Web/personal/mean-app/node_modules/mongoose/lib/schema/objectid.js:165:17)
at Query.cast (/Users/d/Web/personal/mean-app/node_modules/mongoose/lib/query.js:2270:32)
at Query.findOne (/Users/d/Web/personal/mean-app/node_modules/mongoose/lib/query.js:1117:10)
at Query.exec (/Users/d/Web/personal/mean-app/node_modules/mongoose/node_modules/mquery/lib/mquery.js:2181:16)
at Query.exec (/Users/d/Web/personal/mean-app/node_modules/mongoose/lib/query.js:1748:19)
at Function.ClientSchema.statics.load (/Users/d/Web/personal/mean-app/app/models/client.js:80:48)
at exports.client (/Users/d/Web/personal/mean-app/app/controllers/clients.js:15:12)
at paramCallback (/Users/d/Web/personal/mean-app/node_modules/express/lib/router/index.js:151:7)
at param (/Users/d/Web/personal/mean-app/node_modules/express/lib/router/index.js:133:11)
控制器/ clients.js:
exports.client = function(req, res, next, id) {
Client.load(id, function(err, client) {
if (err) return next(err);
if (!client) return next(new Error('Failed to load client ' + id));
req.client = client;
next();
});
};
模型/ client.js:
ClientSchema.statics.load = function(id, cb) {
this.findOne({ _id: id }).populate('user').exec(cb);
};
当我通过mongo shell手动插入客户端(db.clients.save({ name: "Bob" })
)时,它会保存并显示在Node中,但当我通过Angular视图进行编辑时,它无法保存,给我一个类似的错误:
TypeError: Cannot read property 'id' of undefined
我想也许这意味着我的后端代码被找到了,而前端代码没有将所有必要的数据传递给后端。供参考:
公开/ JS /控制器/ clients.js
angular.module('mean.clients').controller('ClientsController', ['$scope', '$routeParams', '$location', 'Global', 'Clients', function ($scope, $routeParams, $location, Global, Clients) {
$scope.global = Global;
$scope.create = function() {
var client = new Clients({
name: this.name,
contactName: this.contactName
});
client.$save(function(response) {
$location.path('clients/' + response._id);
});
this.name = '';
this.contactName = '';
};
// etc.
}]);
公开/ JS /服务/ clients.js
angular.module('mean.clients').factory('Clients', ['$resource', function($resource) {
return $resource('clients/:clientId', {
clientId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}]);
答案 0 :(得分:-1)
您需要在客户端对象中包含_id。