node.js MongoError: '$push' 中以美元 ($) 为前缀的字段 '$push' 对存储无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34795984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage
提问by getglad
I am trying to upserta dataset to a Mongo collection.
我正在尝试将upsert数据集转换为 Mongo 集合。
- The intended document may or may not exist.
- If it does exist, it will have at least one item in an embedded document (zips), and should append to that document rather than overwrite it.
- If it does not exist, it should insert the new document to the collection.
- 预期的文件可能存在也可能不存在。
- 如果它确实存在,它将在嵌入的文档 (zip) 中至少包含一项,并且应该附加到该文档而不是覆盖它。
- 如果它不存在,它应该将新文档插入到集合中。
When I run the below code, I am getting an error: MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage.
当我运行以下代码时,出现错误: MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage.
I put this together based on the docs: https://docs.mongodb.org/getting-started/node/update/#update-multiple-documents
我根据文档将其放在一起:https: //docs.mongodb.org/getting-started/node/update/#update-multiple-documents
Versions: MongoDB (windows) = 3.2.0; mongodb (npm package) = 2.1.4
版本:MongoDB(Windows)= 3.2.0;mongodb(npm 包)= 2.1.4
var query = {
county: aCountyName,
state: aStateName
}
var params = {
'$set': {
county: 'Boone',
state: 'MO',
'$push': {
zips: {
'$each': [ '65203' ]
}
}
}
}
(could also be)
var params = {
'$set': {
county: 'Pierce',
state: 'WA',
'$push': {
zips: {
'$each': [ '98499', '98499' ]
}
}
}
}
db.collection(collectionName).updateMany(query, params, {'upsert': true},
function(err, results) {
callback();
}
);
回答by Owain Williams
I don't think $pushis valid within a $set. Instead try adding it as another parameter, e.g.:
我认为$push在$set. 而是尝试将其添加为另一个参数,例如:
var params = {
'$set': {
county: 'Pierce',
state: 'WA'
},
'$push': {
zips: {
'$each': ['98499',
'98499']
}
}
}
回答by styvane
The reason is because you didn't close the }so MongoDB think $pushis a field's name and as mentioned in the documentation:
原因是因为你没有关闭}所以 MongoDB 认为$push是一个字段的名称和文档中提到的:
Field names cannot contain dots (i.e. .) or null characters, and they must not start with a dollar sign (i.e. $).
字段名称不能包含点(即 .)或空字符,并且它们不能以美元符号(即 $)开头。
var query = {
county: aCountyName,
state: aStateName
};
var params = {};
params['$set'] = { county: 'Boone', state: 'MO' };
params['$push'] = { zips: { '$each': [ '65203' ] } };
Then:
然后:
db.collection(collectionName).updateMany(query, params, {'upsert': true},
function(err, results) {
callback();
}
);

