0

Whenever i try to save my user object which is:

{
  "dtUpdate": "2016-06-08T11:32:01.442Z",
  "username": "JorgeFerrari",
  "password": "kenshin01",
  "email": "joorge.ferrari@gmail.com",
  "company": null,
  "dtCreate": "2016-06-08T11:32:01.442Z",
  "_id": "57580231dfd7b61c2184dd64",
  "flags": {
    "active": true
  },
  "contacts": [
    "57580231dfd7b61c2184dd66",
    "57580231dfd7b61c2184dd67"
  ],
  "address": [
    "57580231dfd7b61c2184dd65"
  ],
  "info": {
    "name": "Jorge Ferrari",
    "dateOfBirth": "2016-06-07T00:00:00.000Z",
    "gender": "M"
  }
}

I'm returned the following errors:

{
  "message": "User validation failed",
  "name": "ValidationError",
  "errors": {
    "contacts": {
      "message": "Cast to Array failed for value \"[object Object],[object Object]\" at path \"contacts\"",
      "name": "CastError",
      "kind": "Array",
      "value": [
        {
          "type": 51,
          "value": "(47) 9685-3200",
          "main": true
        },
        {
          "type": 2,
          "value": "(47) 3521-8717",
          "main": false
        }
      ],
      "path": "contacts",
      "reason": {
        "message": "Cast to ObjectId failed for value \"[object Object]\" at path \"contacts\"",
        "name": "CastError",
        "kind": "ObjectId",
        "value": {
          "type": 51,
          "value": "(47) 9685-3200",
          "main": true
        },
        "path": "contacts"
      }
    },
    "address": {
      "message": "Cast to Array failed for value \"[object Object]\" at path \"address\"",
      "name": "CastError",
      "kind": "Array",
      "value": [
        {
          "street": "Rua 1601",
          "nr": "118",
          "neighborhood": "Centro",
          "complement": "Apto 702",
          "zipcode": "88330807",
          "city": "Balneário Camboriú",
          "state": "SC",
          "main": true
        }
      ],
      "path": "address",
      "reason": {
        "message": "Cast to ObjectId failed for value \"[object Object]\" at path \"address\"",
        "name": "CastError",
        "kind": "ObjectId",
        "value": {
          "street": "Rua 1601",
          "nr": "118",
          "neighborhood": "Centro",
          "complement": "Apto 702",
          "zipcode": "88330807",
          "city": "Balneário Camboriú",
          "state": "SC",
          "main": true
        },
        "path": "address"
      }
    }
  }
}

I really don't understand whats makes this error, and i'm in need of help. In my Schema, both, address and contact fields are with type: Schema.Types.ObjectId

As asked in the comment here is my Schema. (Sorry about the amount of code)

var userSchema   = new Schema({
    username: { type: String, required: true, unique: true, index: true },
    password: { type: String, required: true , minlength: 128, maxlength: 128 },
    email: { type: String, required: true, unique: true, index: true },
    profileImage: { type: String },
    company: { type: Schema.Types.ObjectId, ref: 'Company' },
    info: {
        name: { type: String, required: true },
        dateOfBirth: { type: Date },
        gender: { type: String, enum: ['M', 'F'] }
    },
    address: [{ 
        type: Schema.Types.ObjectId, ref: 'Address' 
    }],
    contacts: [{
        type: Schema.Types.ObjectId, ref: 'Contact' 
    }],
    flags: {
        active: { type: Boolean, required: true },
        deleted: { type: Boolean },
        blocked: { type: Boolean },
        newPassword: { type: Boolean }
    },
    login: {
        lastDate: { type: Date },
        lastIp: { type: String }
    },
    dtCreate: { type: Date },   
    dtUpdate: { type: Date }
});

The functions that makes the saving:

createUser: function(req, res) {

        var _user = new Models.User(req.body);

        _user.password = crypto.createHash(_user.password);

        for (var index in req.body.address) {
            var _address =  new Models.Address(req.body.address[index]);
            _user.address.push(_address._id);
            _address.save(function(err){

            });
        }

        for (var index in req.body.contacts) {
            var _contact = new Models.Contact(req.body.contacts[index]);
            _user.contacts.push(_contact._id);
            _contact.save(function(err) {

            });
        }

        var _dateCreation = new Date();

        _user.dtCreate = _dateCreation;
        _user.dtUpdate = _dateCreation;

        _user.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                var _returnUser = Models.User.findById(_user._id, function(err, user) {
                    if (err)  { res.send(err); }
                    else { res.send(user); }
                });
            }
        });
        return;
    },
Jorge Ferrari
  • 152
  • 3
  • 11
  • Could you please show Schema? – jano Jun 08 '16 at 12:06
  • @jano edited to show the schema. – Jorge Ferrari Jun 08 '16 at 12:12
  • See if [this question](http://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id) can help you. – Shrabanee Jun 08 '16 at 12:31
  • The example object you provide doesn't match the errors. The errors have each element of `contacts` and `address` populated with data rather than plain `mongoose.Schema.Types.ObjectId` you have in the sample. Maybe post the code doing the saving as well because there is something amiss. – Matt Jun 08 '16 at 12:50
  • Added the requested code @Matt – Jorge Ferrari Jun 08 '16 at 15:14

1 Answers1

0

When the User is created from the complete request body, address and contacts are populated with data.

You then push the newly created Address and Contact ObjectID's onto the end of this data.

_user.contact => [{blob}, {blob}, ObjectID, ObjectID]
_user.address => [{blob}, ObjectID]

The original data causes validation to fail.

When you construct User you need to remove contact and address.

If you have lodash or underscore:

var data = _.omit(req.body,'contact','address')

In pure js, maybe delete them (Although I'm sure deleting from req.body is going to come back and bite you somewhere, someday)

var contact = req.body.contact;
var address = req.body.address;
delete req.body.contact
delete req.body.address
var _user = new Models.User(req.body);
Matt
  • 68,711
  • 7
  • 155
  • 158