Meteor.js 遍历数组以检查值是否已存在于 collection 文档中
Meteor.js Loop over an array to check if value already exists in collection documents
我找不到这个问题的答案。我看到的所有示例都是在 collection 上查找字段 Number
的值 123456
。
但是我想知道是否可以在整个 collection 文档中搜索数组中的数字。
例如,这是我 collection:
的第一个文档
{
"_id": "Qfjgftt7jLh3njw8X",
"reference": 102020026, // Field that I want to check
"type": "Moradias",
"n_beds": 5,
"price": 30000,
"departement": "Portalegre",
"city": "Ponte de Sor",
"street_name": "Rua do Comércio, CE",
"l_surface": 248,
"is_exclusive": true
}
客户正在导入一个 XLSX 文件,该文件已转换为 JSON,并添加到我的 collection,因此 reference
号码由客户插入。
然后我想遍历我的 JSON,(可能有不止一个引用)获取客户端导入的引用,并检查这些引用是否已经存在于我的 collection 文档之一中。之后我会抛出一个错误。
我知道我可以 Collection.find({reference: '102020026'})
但问题是我的 collection.
中可以有 100 多个不同的引用
我希望这是有道理的,并且没有在其他地方得到答复。
提前致谢!
您可能想要使用 $in
mongo 运算符 (see doc) 来查找给定数组的所有文档:
const ids = [
102020026,
102021407,
102023660,
];
Collection.find({reference: {$in: ids}});
这 returns 所有文档,其中 reference
匹配 ìds 数组中给定的数字之一。
我的情况是解决方案:
使用@Jankapunkt 回答的Mongo 运算符$in
:
let arr = [];
for (let c = 0; c< myJSON.length; c++) {
arr.push(myJSON[c].reference);
}
if(Collection.find({reference: {$in: arr}}).count() > 1) {
alert(`Reference ${arr} already exists`);
throw new Error('Duplicated reference');
}
如果没有 $in
Mongo 运算符,只需使用 for
循环,结果相同:
for (let c = 0; c < myJSON.length; c++) {
if (Collection.find({reference: myJSON[c].reference}).count > 1) {
alert(`Reference ${arr} already exists`);
throw new Error('Duplicated reference');
}
}
我找不到这个问题的答案。我看到的所有示例都是在 collection 上查找字段 Number
的值 123456
。
但是我想知道是否可以在整个 collection 文档中搜索数组中的数字。
例如,这是我 collection:
{
"_id": "Qfjgftt7jLh3njw8X",
"reference": 102020026, // Field that I want to check
"type": "Moradias",
"n_beds": 5,
"price": 30000,
"departement": "Portalegre",
"city": "Ponte de Sor",
"street_name": "Rua do Comércio, CE",
"l_surface": 248,
"is_exclusive": true
}
客户正在导入一个 XLSX 文件,该文件已转换为 JSON,并添加到我的 collection,因此 reference
号码由客户插入。
然后我想遍历我的 JSON,(可能有不止一个引用)获取客户端导入的引用,并检查这些引用是否已经存在于我的 collection 文档之一中。之后我会抛出一个错误。
我知道我可以 Collection.find({reference: '102020026'})
但问题是我的 collection.
我希望这是有道理的,并且没有在其他地方得到答复。
提前致谢!
您可能想要使用 $in
mongo 运算符 (see doc) 来查找给定数组的所有文档:
const ids = [
102020026,
102021407,
102023660,
];
Collection.find({reference: {$in: ids}});
这 returns 所有文档,其中 reference
匹配 ìds 数组中给定的数字之一。
我的情况是解决方案:
使用@Jankapunkt 回答的Mongo 运算符$in
:
let arr = [];
for (let c = 0; c< myJSON.length; c++) {
arr.push(myJSON[c].reference);
}
if(Collection.find({reference: {$in: arr}}).count() > 1) {
alert(`Reference ${arr} already exists`);
throw new Error('Duplicated reference');
}
如果没有 $in
Mongo 运算符,只需使用 for
循环,结果相同:
for (let c = 0; c < myJSON.length; c++) {
if (Collection.find({reference: myJSON[c].reference}).count > 1) {
alert(`Reference ${arr} already exists`);
throw new Error('Duplicated reference');
}
}