这是我从console.log(objects)
得到的东西:
{
"_id" : "5bb20d7556db6915846da55f",
"gallary" : {
"profilepic" : [
"1",
"2"
]
}
},
{
"_id" : "5bb20d7556db6915846da55f",
"gallary" : {
"profilepic" : [
"3",
"4"
]
}
}
我有一个输入数组,例如:let uniqueIDs = ["0","1","10"]
。我必须检查gallary.profilepic
是否给定输入值可用?假设不可用,则意味着我必须推入一个数组并返回结果。
我的代码:
let uniqueIDs = ["0","1","10"]
db.Gallary.find()
.forEach(function(objects){
console.log(objects);
// Here your JS code has to come
})
预期输出:
["0", "10"]
答案 0 :(得分:0)
过滤UPIDs
数组,检查其中的哪些项目未包含在regularStudent
数据的members
属性中:
let UPIDs = ["0","1","10"];
const data = [{
"_id" : "5bb20d7556db6915846da55f",
"members" : {
"regularStudent" : [
"1",
"2"
]
}
},
{
"_id" : "5bb20d7556db6915846da55f",
"members" : {
"regularStudent" : [
"3",
"4"
]
}
}];
const regularStudents = data.map(d => d.members.regularStudent).flat();
console.log(UPIDs.filter(a => !regularStudents.includes(a)));
答案 1 :(得分:0)
您可以将所有ID组成一个数组(在我的示例中,我使用了reduce
),然后filter
列出了该数组中未出现的UPID中的所有那些元素。
const data = [{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":["1","2"]}},{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":["3","4"]}}];
const UPIDs = ["0","1","10"];
// Concatenate the ids in the data together
const ids = data.reduce((acc, c) => acc.concat(c.members.regularStudent), []);
// `filter` out the elements in UPIDs that aren't in the ids array
const out = UPIDs.filter(el => !ids.includes(el));
console.log(out);
为澄清起见进行更新:
这是您的代码与我的代码的结合:
let UPIDs = ['0', '1', '10'];
db.Groups.find().forEach(function(objects){
const ids = objects.reduce((acc, c) => acc.concat(c.members.regularStudent), []);
const out = UPIDs.filter(el => !ids.includes(el));
console.log(out);
});
答案 2 :(得分:0)
我首先要获取数据库中与您要输入的数据匹配的所有值(否则它将加载您的所有集合条目),然后查看缺少的字符串。最后,如有必要,推送一个新条目。
const UPIDs = ['0','1','10'];
const entries = await db.Groups.find({
'members.regularStudent': {
$in: UPIDs,
},
});
// Get the strings that are not in the DB
const missing = UPIDs.filter(x => !entries.some(y => y.members.regularStudent.includes(x)));
// Push the missing str in DB
if (missing.length) {
const obj = new model({
members: {
regularStudent: missing,
},
});
// ...
}
const UPIDs = ['0', '1', '10'];
// Thx to @Andy
const entries = [{"_id":"5bb20d7556db6915846da55f","members":{"regularStudent":['1', '2']}}];
/*
const entries = await db.Groups.find({
'members.regularStudent': {
$in: UPIDs,
},
});
*/
// Get the strings that are not in the DB
const missing = UPIDs.filter(x => !entries.some(y => y.members.regularStudent.includes(x)));
// Push the missing str in DB
if (missing.length) {
console.log('Add new data for values', missing);
}