【问题标题】:CastError: Cast to string failed for valueCastError:转换为字符串的值失败
【发布时间】:2018-11-06 00:53:18
【问题描述】:

我想创建一个交易模块,在成功交易后,用户文档(在这种情况下是用户向另一个用户汇款)也会被更新。

一个。在 user.js(这是用户模型)中,除了姓名、密码、电子邮件(等)之外,我创建了这个属性,它将保存各个用户的交易相关历史记录。请看我是如何使用它的:

transaction_history:[{
            transactionid:String,
            timestamp:String,
            type:String,
            balance:Number,
            status:String

        }]

b.当发件人点击表单中的发送按钮时,会创建一个交易文档,然后用户文档(此处为发件人)应与交易信息一起更新。

//create transaction document, works fine
Transaction.create({transactionid:uniqid(),
                timestamp:moment().format(datemask),
                amount:balance,
                sender:sendfrom,
                receiver:sendto,
                status:"done"
}, function(err, tr){
    if(err) throw err;
    else {

        //I want sender document to update with transaction info
        User.findOne({email:sendfrom}, function(err, sendfrom){
            if(err) {console.log("error at sender side");}
            else 
            if(sendfrom!=null){
                // console.log("tr: "+tr); //fine
                sendfrom.balance-=balance;
                sendfrom.transaction_history.push({

                     transactionid:tr.transactionid, 


                    // timestamp:tr.timestamp,
                    // type:"debit",
                    // balance:tr.amount,
                    // status:tr.status 

                }
                );
                sendfrom.save();
                console.log("sender's current balance is: "+sendfrom.balance);


            };
            });
            }});

c。但后来我明白了:

events.js:163
  throw er; // Unhandled 'error' event
  ^
CastError: Cast to string failed for value "{ transactionid: '1amhrummxjhnhv0w4' }" at path "transaction_history"

为什么会出现这个错误?我需要你的建议!谢谢

【问题讨论】:

  • 你传入一个 JSON 字符串 "{ transactionid: '1amhrummxjhnhv0w4' } 而不仅仅是值 '1amhrummxjhnhv0w4'

标签: node.js mongoose nosql


【解决方案1】:

您不能将“类型”一词用作对象。只需重命名为“something_type”之类的其他名称即可。

【讨论】:

  • 你可以,只需在架构内执行type:{type:<your type>}
【解决方案2】:

问题的根源在于我定义 transaction_history 属性的方式。这应该是语法上的对象数组[{}],但后来我把它的类型写成了字符串。因此,当我尝试将字符串作为“type”的值插入时,会引发错误,无法将字符串推送到“transaction_history”对象。要解决它,只需要删除类型属性。在对象中使用保留字作为键是我的错误。所以我用模型中的其他东西替换了“类型”。而已!

【讨论】:

    【解决方案3】:

    就我而言:

    CastError: Cast to String failed for value "[ 'whateverValue_1', 'whateverValue_2' ]" at path "name"
    

    问题是我的表单 html 名称相同的单词...

    即:

    <input name = "name"> Name 
    <input city = "name"> City
    

    寻找我的错误,我留给你其他可以帮助像我一样的新手:

    typemodel 之类的词永远不必在模型 Schema 中作为主要关键字!

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2021-06-27
      • 2021-09-05
      • 2019-04-18
      • 2023-04-09
      • 2021-03-14
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多