无法在node.js中使用mongoose保存文档关系

时间:2016-06-08 12:01:40

标签: node.js mongodb mongoose

每当我尝试保存我的用户对象时:

{
  "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"
  }
}

我返回了以下错误:

{
  "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"
      }
    }
  }
}

我真的不明白什么是这个错误,我需要帮助。在我的Schema中,地址和联系人字段都是类型:Schema.Types.ObjectId

正如评论中所述,这是我的架构。 (抱歉代码数量)

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 }
});

进行保存的功能:

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;
    },

1 个答案:

答案 0 :(得分:0)

从完整的请求正文创建User后,addresscontacts会填充数据。

然后,您将新创建的AddressContact ObjectID推送到此数据的末尾。

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

原始数据导致验证失败。

构建User时,您需要删除contactaddress

如果您有lodash或下划线:

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

在纯粹的js中,可能delete他们(虽然我确定从req.body删除会在某个时候回来咬你,

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);