Mongoose-Mongo {[CastError:Cast to Object因值而失败" ..."在路径" ..."

时间:2016-11-10 01:07:49

标签: node.js mongodb mongoose

我有这个错误:

{ [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:......)但它仍然给了我那个错误

1 个答案:

答案 0 :(得分:1)

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

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