mongoose将id数组添加到对象

时间:2016-11-19 14:31:10

标签: node.js mongodb mongoose

我试图通过引用用户和排名来保存组。 usersranks是id' s的数组。但是,当我发布帖子请求时,似乎说组验证失败了。我的参考文献出了什么问题?

router.post('/:users/:game/:ranks/:age/:quantity/:usercount', function(req, res, next) {

  var params = req.params;
  var ranks = params.ranks.split(',');
  var users = params.users.split(',');


  var group = new Group({
    users: users,
    game: params.game,
    ranks: ranks,
    quantity: params.quantity,
    age_above: params.age,
    userCount: params.usercount
  });

  group.save(function(err, object) {
    if (err) {
      res.send(err);
    } else {
      User.findByIdAndUpdate(params.id, {$set:{group:object.id}}, {new: true}, function(err, doc){
        if(err){
          res.send(err);
        } else {
          res.send(doc);
        }

      }).populate('group');



    }
  });
});

用户架构

var userSchema = new Schema({
  _id: {
    type: SchemaTypes.Long,
    required: true,
    unique: true,
    index: {unique: true}
  },
  name: String,
  birthday: Date,
  country: String,
  image: String,
  group: { type: Schema.Types.ObjectId, ref: 'Group'},
  games: [{
    game: { type: Schema.Types.ObjectId, ref: 'Game'},
    rank: { type: Schema.Types.ObjectId, ref: 'Ladder'},
    userName: String
  }],
  friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  created_at: Date,
  updated_at: Date
});

错误消息

{
  "message": "Group validation failed",
  "name": "ValidationError",
  "errors": {
    "users": {
      "message": "Cast to Array failed for value \"[ '10210697939629739' ]\" at path \"users\"",
      "name": "CastError",
      "kind": "Array",
      "value": [
        "10210697939629739"
      ],
      "path": "users",
      "reason": {
        "message": "Cast to ObjectId failed for value \"10210697939629739\" at path \"users\"",
        "name": "CastError",
        "kind": "ObjectId",
        "value": "10210697939629739",
        "path": "users"
      }
    }
  }
}

0 个答案:

没有答案