TypeError:无法使用'in'运算符在[{}]中搜索'_id'

时间:2014-12-20 04:59:55

标签: javascript mongodb mongoose

我有一个如下创建的模型

var AddressSchema = new Schema({
  category: {type: String,  default: 'home'},
  lines: {type: String },
  city: {type: String}  
});


/**
 * Employee Schema
 */
var EmployeeSchema = new Schema({
  created: {
    type: Date,

    default: Date.now
  },
  name: {
    type: String,
    required: true,
    trim: true
  },
  address: [AddressSchema],
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

以下是controller.js中的代码

exports.create = function(req, res) {
  console.log('in create');
  var employee = new Employee(req.body);
  employee.user = req.user;
  var address = new Address(req.body.address);
  employee.address = [address];
  console.log(employee);
  console.log(req.body);

  employee.save(function(err) {
    if (err) {
        console.log(err);

      return res.status(500).json({
        error: 'Cannot save the employee'
      });
    }
    res.json(employee);

  });
};

我的控制台中写的日志是

{ user: 5493dabf682b42be6af784b1,
  name: 'santhu',
  _id: 5495010203fa1e000068808b,
  address: [ { _id: 5495010203fa1e000068808c, category: 'home' } ],
  created: Sat Dec 20 2014 10:24:26 GMT+0530 (IST) }
{ name: 'santhu', address: '{}' }
[TypeError: Cannot use 'in' operator to search for '_id' in {}]

为什么我收到此错误?我搜索了这个错误,当我尝试在预期对象时保存字符串时会发生这种情况。我正在保存正确的对象,你可以在日志中看到。为什么我仍然面临这个问题?

1 个答案:

答案 0 :(得分:2)

这是因为您的req.body包含地址:' {}'如果你写

,那就是字符串而不是数组而不是对象
 var body={ name: 'santhu', address: []}; //and not { name: 'santhu', address: '{}'}
 var employee = new Employee(body);

它会正常工作