如何列出所有记录以查看它们是否重复?
How can I list all the records to see if they are duplicated?
我有一个无法解决的问题。我在 MongoDB 中有一个 table,这是结构:
const shopEconomy = new mongoose.Schema({
guildID: { type: String },
name: { type: String },
value: { type: Number },
description: { type: String },
rolereq: { type: String },
roleadd: { type: String },
roleremove: { type: String },
buyinfo: { type: String }
});
我需要列出 table (shopData.name) 中的所有名称,然后检查数据库中是否存在键入的名称。我尝试执行类似下面的操作,但它不起作用。
const shopData = await shopEconomy.find({ guildID: message.guild.id });
let categories = [];
let data = new Object();
for(const i in shopData){
data += `${shopData[i].name}\n`
categories.push(data)
}
有人可以看看这个并帮助我吗?
这里的部分问题来自 for...in
loop which treats shopData
as an object and loops over all properties of it. Instead try using a for...of
循环的使用,该循环将 shopData
视为一个数组并遍历其中的所有对象。
...
for(const i of shopData) {
data += `${i.name}\n`
...
}
另请参阅 JavaScript 循环中的 on for...in
vs for...of
and this question。
问题的标题与问题的描述不完全相符。根据描述,我们假设键入的名称已分配给 var typedName
.
我们还假设您已将 shopEconomy
架构绑定到一个模型,该模型实际上将与名为 shopData
的 mongodb collection 进行交互。然后这将迭代 shopData
:
中的所有文档
var found = false;
cursor = db.shopData.find(); // get EVERYTHING
cursor.forEach(function(doc) {
print(doc['name']);
if(doc['name'] == typedName) {
found = true;
}
});
if(found) {
print(typedName,"was found");
}
OP 可能希望在 collection 中找到重复的名称,此管道将为此工作:
db.shopData.aggregate([
{$group: {_id: '$name', N:{$sum:1}} },
{$match: {'N':{$gt:1}}}
]);
我有一个无法解决的问题。我在 MongoDB 中有一个 table,这是结构:
const shopEconomy = new mongoose.Schema({
guildID: { type: String },
name: { type: String },
value: { type: Number },
description: { type: String },
rolereq: { type: String },
roleadd: { type: String },
roleremove: { type: String },
buyinfo: { type: String }
});
我需要列出 table (shopData.name) 中的所有名称,然后检查数据库中是否存在键入的名称。我尝试执行类似下面的操作,但它不起作用。
const shopData = await shopEconomy.find({ guildID: message.guild.id });
let categories = [];
let data = new Object();
for(const i in shopData){
data += `${shopData[i].name}\n`
categories.push(data)
}
有人可以看看这个并帮助我吗?
这里的部分问题来自 for...in
loop which treats shopData
as an object and loops over all properties of it. Instead try using a for...of
循环的使用,该循环将 shopData
视为一个数组并遍历其中的所有对象。
...
for(const i of shopData) {
data += `${i.name}\n`
...
}
另请参阅 JavaScript 循环中的 for...in
vs for...of
and this question。
问题的标题与问题的描述不完全相符。根据描述,我们假设键入的名称已分配给 var typedName
.
我们还假设您已将 shopEconomy
架构绑定到一个模型,该模型实际上将与名为 shopData
的 mongodb collection 进行交互。然后这将迭代 shopData
:
var found = false;
cursor = db.shopData.find(); // get EVERYTHING
cursor.forEach(function(doc) {
print(doc['name']);
if(doc['name'] == typedName) {
found = true;
}
});
if(found) {
print(typedName,"was found");
}
OP 可能希望在 collection 中找到重复的名称,此管道将为此工作:
db.shopData.aggregate([
{$group: {_id: '$name', N:{$sum:1}} },
{$match: {'N':{$gt:1}}}
]);