TypeError:无法使用"in"运算符在[{}]中搜索"_id" [英] TypeError: Cannot use 'in' operator to search for '_id' in [{}]
本文介绍了TypeError:无法使用"in"运算符在[{}]中搜索"_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下创建的模型
I have a model created as follows
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中的代码
Following is the code in 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);
});
};
在我的控制台中写的日志是
Log written in my console is
{ 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 {}]
为什么会出现此错误?我搜索了此错误,当我尝试保存期望对象的字符串时发生了此错误.我正在保存适当的对象,正如您在日志中看到的那样.为什么我仍然面临这个问题?
Why am I getting this error? I searched for this error and it happens when I try to save string when it expects object. I am saving proper object as you can see in logs. Why am I still facing this problem?
推荐答案
这是因为您的请求正文包含地址:"{}",该地址不是字符串,也不是对象,如果您编写
it is because your req.body contains address: '{}' which is string not array and not object if you write
var body={ name: 'santhu', address: []}; //and not { name: 'santhu', address: '{}'}
var employee = new Employee(body);
它将正常工作
这篇关于TypeError:无法使用"in"运算符在[{}]中搜索"_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文