Arrays 错误{[CastError:Cast to ObjectId在路径“u id”处的值失败]
我一直在学习如何填充我拥有的引用数组Arrays 错误{[CastError:Cast to ObjectId在路径“u id”处的值失败],arrays,node.js,mongodb,mongoose,http-get,Arrays,Node.js,Mongodb,Mongoose,Http Get,我一直在学习如何填充我拥有的引用数组 Error! { [CastError: Cast to ObjectId failed for value "blah" at path "_id"] message: 'Cast to ObjectId failed for value "blah" at path "_id"', name: 'CastError', type: 'ObjectId', value: 'blah', path: '_id' } 数组中的值为blah
Error! { [CastError: Cast to ObjectId failed for value "blah" at path "_id"]
message: 'Cast to ObjectId failed for value "blah" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'blah',
path: '_id' }
数组中的值为blah
。下面是我的尝试:
HTTP Get调用:
$scope.user = Auth.getCurrentUser();
$http.get('/api/users/' + $scope.user._id)
.success(function(data, status, headers, config){
$scope.currentUser = data;
});
用户架构:
var UserSchema = new Schema({
name: String,
username: String,
eventsAttending: [{ type: String, ref: 'Event'}],
});
和HTTP GET函数:
router.get('/:id', controller.getEvents);
exports.getEvents = function(req, res) {
User.findById(req.params.id).populate('eventsAttending').exec(function(err, events){
if(err) {
console.log("Error!", err);
return res.send(500, err);
}
return res.json(200, events);
});
};
老实说,我不太清楚为什么数组中的值被转换成对象Id。我明确指定数组中的内容是字符串,而不是对象Id,后者将引用事件架构。我知道数组中的内容是简单的字符串。知道为什么会发生这种情况吗
编辑:我正在发布一个示例对象。这里是我要填充的eventsAttending数组:
{
"name" : "Jane Doe",
"username" : "jane93",
"eventsAttending" : [
"blah",
"TestEvent",
"Asdf",
"TestEvent2"
]
}
您正在使用
populate
函数,我相信该函数默认情况下会将\u id
引用转换为ObjectId
实例。您是否正在请求/api/users/blah
?blah
不是正确的ObjectId。看起来数组中的包含不是ObjectId的格式。请检查它们。另外,它也是r建议使用Schema.Types.ObjectId
而不是String
。ObjectId使用更小的空间,它不需要从String转换为ObjectId,因此速度更快,并且您不能在其中输入错误的类型值。@foadnostratihabibi我正在请求/api/users/。我的数组中确实包含了您可以从上面的架构中看到的字符串。是否可能在字符串上使用填充而不是对象ID?是的,这是可能的。您能在这里放置数组的真实样本吗?