【问题标题】:Mongoose-Mongo {[CastError: Cast to Object failed for value "..." at path "..."Mongoose-Mongo {[CastError: Cast to Object failed for value "..." at path "..."
【发布时间】:2017-03-23 22:41:05
【问题描述】:

我遇到了这个错误:

{ [ValidationError: Contact validation failed]
  message: 'Contact validation failed',
  name: 'ValidationError',
  errors: 
   { Contact: 
      { [CastError: Cast to Object failed for value "ContactExample" at path "Contact"]
        message: 'Cast to Object failed for value "ContactExample" at path "Contact"',
        name: 'CastError',
        kind: 'Object',
        value: 'ContactExample',
        path: 'Contact',
        reason: undefined },
}
Same for ContactType

我的代码如下:

ContactSchema.js:

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

var Contact = new Schema({
    Contact: {Type: String},
    ContactType: {Type: String}, 
    ContactOwner: {type: String} 

});
module.exports = mongoose.model("Contact", Contact);

路线:

app.post('/newcontact', isLoggedIn, function(req, res) {
    ContactModel.count({"Contact": req.body.Contact}, function(err, result){
        if (result>0) res.send('Contact already taken');
        else{
            var newContact = new ContactModel();   
            console.log(req.body);
            newContact.ContactOwner = req.user.email;
            newContact.Contact = req.body.Contact;
            newContact.ContactType = req.body.ContactType;
            newContact.save(function(err){console.log(err);});
            res.send('Done');
        }
    });
});

我尝试填写“_id”字段并执行 ContactModel(ContactOwner: ......) 但它仍然给我这个错误

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你的架构中type的情况不正确,请将架构定义替换为

    var Contact = new Schema({
        Contact: {type: String},
        ContactType: {type: String}, 
        ContactOwner: {type: String} 
    });
    

    【讨论】:

    • 谢谢,我现在感觉好傻,我太专注于路由的代码而不是架构
    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 2017-02-06
    • 2020-10-21
    • 2021-01-07
    • 2015-08-10
    • 2022-06-14
    • 2013-02-03
    相关资源
    最近更新 更多