【问题标题】:TypeError: Cannot use 'in' operator to search for '_id' in [{}]TypeError:无法使用“in”运算符在 [{}] 中搜索“_id”
【发布时间】:2015-02-19 01:00:13
【问题描述】:

我有一个如下创建的模型

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

为什么会出现此错误?我搜索了这个错误,当我在它需要对象时尝试保存字符串时会发生这种错误。正如您在日志中看到的那样,我正在保存正确的对象。为什么我仍然面临这个问题?

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    这是因为你的 req.body 包含地址:'{}',如果你写的话,它是字符串而不是数组而不是对象

     var body={ name: 'santhu', address: []}; //and not { name: 'santhu', address: '{}'}
     var employee = new Employee(body);
    

    它会正常工作

    【讨论】:

    • 在我展示的示例中,我已经在保存之前替换了地址属性。为什么还是报错?
    • 因为你写的是 var employee = new Employee(req.body);这给出了错误
    • 如果该行有错误,为什么它仍在打印。当它继续打印该行之后的日志时,我认为该行很好,但在保存过程中出错。我错了吗?
    • 在保存期间没有错误,因为您在这一行更改了employee.addressemployee.address = [address];并且在保存时地址不会被刺痛。如果您不更改地址,您将在保存时收到错误
    猜你喜欢
    • 2013-04-05
    • 2013-06-10
    • 2013-01-15
    • 2018-05-17
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    相关资源
    最近更新 更多