Javascript TypeError:无法使用';在';操作员搜索'_id';在[{}]
我创建了一个模型,如下所示Javascript TypeError:无法使用';在';操作员搜索'_id';在[{}],javascript,mongodb,mongoose,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, defau
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 {}]
为什么我会犯这个错误?我搜索了这个错误,当我试图在字符串需要对象时保存它时,就会发生这个错误。我正在保存您在日志中看到的适当对象。为什么我仍然面临这个问题?这是因为您的req.body包含地址:“{}”,如果您写入,它不是数组,也不是对象
var body={ name: 'santhu', address: []}; //and not { name: 'santhu', address: '{}'}
var employee = new Employee(body);
它可以正常工作在我展示的示例中,我在保存之前已经替换了address属性。为什么它仍然给出错误?因为您编写了var employee=newemployee(req.body);这就给出了错误,如果那一行有错误,为什么它还在打印。当它继续打印该行之后的日志时,我认为该行很好,但错误在保存期间。我错了吗?在保存期间没有错误,因为您更改了此行中的employee.address employee.address=[address];并且在保存时地址不会被刺痛。若你们不改变地址,你们将在保存时收到错误