本文介绍了错误:ValidationError:CastError:Cast to ObjectID 的值失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

看来我一定是在 Mongoose 模型或传递给路由的参数之一中犯了错误.

It seems I must have made a mistake in my Mongoose Model or in one of the parameters that are passed to the route.

我对 angular2 架构还很陌生,所以错误可能很明显.

I am fairly new to the angular2 architecture, so the mistake might be quite obvious.

错误:

  ERROR: ValidationError: CastError: Cast to ObjectID failed for value "{ title: 'das',
      username: 'John',
      choice1: 'FSDAFASDF',
      choice2: 'FDSAFD',
      counter1: 11,
      counter2: 0,
      pollId: '5920598ade7567001170c810',
      userId: '591c15b3ebbd170aa07cd476' }" at path "poll"

代码:

路线

router.patch('/', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    User.findById(decoded.user._id, function (err, user) {
      user.votes = req.body.votes;
      user.save(function(err, result) {
          if (err) {
              console.log("ERROR: "+err);
              return res.status(500).json({
                  title: 'An error occurred',
                  error: err
              });
          }
          res.status(201).json({
              poll: 'Vote Saved',
              obj: result
          });
      });
   });
});

模型/用户:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    password: {type: String, required: true},
    email: {type: String, required: true, unique: true},
    polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}],
    votes: [{
      poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
      choice: {type: Number},
    }],
});

schema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('User', schema);

模型/民意调查

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

var User = require('./user');

var schema = new Schema({
    title: {type: String, required: true},
    choice1: {type: String, required: true},
    choice2: {type: String, required: true},
    counter1: {type: Number, required: true},
    counter2: {type: Number, required: true},
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

schema.post('remove', function (poll) {
    User.findById(poll.user, function (err, user) {
        user.polls.pull(poll);
        user.save();
    });
});

module.exports = mongoose.model('Poll', schema);

router.patch('/', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    console.log("VALID ID ? :"+mongoose.Types.ObjectId.isValid(decoded.user._id));
    console.log("DECODED USER ID:"+ decoded.user._id);
    User.findByIdAndUpdate(decoded.user._id, {votes: req.body.votes}, function (err, user) {
      user.save(function(err, result) {
          if (err) {
              console.log("ERROR: "+err);
              return res.status(500).json({
                  title: 'An error occurred',
                  error: err
              });
          }
          res.status(201).json({
              poll: 'Vote Saved',
              obj: result
          });
      });
   });
});

推荐答案

我深思熟虑地猜测是这段特定的代码导致了问题:

I'm thoughtfully guessing that this particular piece of code is what causes the issue:

    ...
    User.findById(decoded.user._id, function (err, user) {
      user.votes = req.body.votes;
      user.save(function(err, result) {
    ...

mongoose 试图重新保存模型并用一个普通字符串覆盖它的 _id 属性,而它应该是 ObjectId 的一个实例.

mongoose is trying to resave the model and overwrite it's _id property with a plain string, whereas it should be an instance of the ObjectId.

不要使用保存来更新您的模型,请尝试使用 findByIdAndUpdate 代替.如果这有效,那么我的猜测是正确的.

Instead of using save to update your model, please try to use findByIdAndUpdate instead. If this is working, than my guess would be correct.

User.findByIdAndUpdate(decode.user._id, {votes: req.body.votes}, function (err, user) {

或者,手动将字符串 _id 转换为 ObjectId

Or, cast the string _id into an ObjectId manually

    ...
    User.findById(decoded.user._id, function (err, user) {
      user.votes = req.body.votes;
      user._id = mongoose.Types.ObjectId(user._id);
      user.save(function(err, result) {
    ...

首选第一个.

这篇关于错误:ValidationError:CastError:Cast to ObjectID 的值失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:07
查看更多