问题描述
我正在尝试通过从文件中读取数据并使用'update'方法来更新数据库中的数据.
I'm trying to update data in a database by reading data from a file and using the 'update' method.
var Model = require('./dbIndex').Model
BioMetrics.update({AID: AID},
{$pushAll: {
attr1: data[5] === '' ? undefined : {val: data[5], dt: date},
attr2: data[6] === '' ? undefined : {val: data[6], dt: date},
attr3: data[10] === '' ? undefined : {val: data[10], dt: date}
}}, options, callback);
运行此命令时,出现以下错误:TypeError: Cannot read property 'constructor' of undefined
When I run this I get the following error:TypeError: Cannot read property 'constructor' of undefined
Mongo不知道undefined
是什么意思?我的印象是,当undefined为true时,Mongo只会忽略该属性.
Mongo does not know what undefined
means? I had the impression that when undefined is true Mongo just ignores that attribute.
有人可以解释这里发生了什么吗?
Can someone explain what's happening here?
推荐答案
MongoDB可能会忽略设置为undefined
的字段,但是Mongoose却没有,因为它具有可使用的架构,并将尝试将值转换为正确的类型按照架构中的定义.
MongoDB may ignore fields set to undefined
, but Mongoose doesn't as it has a schema to work from and will try and cast values to the right types as defined in the schema.
在这种情况下,您可以通过编程方式建立$pushAll
值,使其仅包含所需的属性:
For a case like this you can build up your $pushAll
value programmatically to only include the attributes you want:
var value = {};
if (data[5] !== '') {
value.attr1 = {val: data[5], dt: date};
}
if (data[6] !== '') {
value.attr2 = {val: data[6], dt: date};
}
if (data[10] !== '') {
value.attr3 = {val: data[10], dt: date};
}
BioMetrics.update({AID: AID}, {$pushAll: value}, options, callback);
这篇关于具有TypeError的mongooseJS:无法读取未定义的属性“构造函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!