如何使用 Nodejs、mongodb 和 express 在对象数组的数组中使用计数查询?
How to use count query in an array of object array using Nodejs , mongodb and express?
我有 2 个模型,一个称为 User,另一个称为 Item。项目数组分配给每个用户(每个用户有 5 个项目)。通过每个用户的会话,用户可以将项目分类为合格或不合格或其中 none 个。这是模型:
const ItemSchema = new Schema({
title: {
type: String,
},
classification: {
type: String,
}
});
//Create the User Schema
const UserSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
items: [ItemSchema],
});
UserSchema.pre("save", function (next) {
this.items = [];
this.items.push({
title: "Item 1",
classification: ""
});
this.items.push({
title: "Item 2",
classification: ""
});
this.items.push({
title: "Item 3",
classification: ""
});
next();
});
module.exports = User = mongoose.model("users", UserSchema);
如您所见,用户的项目具有分类 属性,可以在其中写入“合格”或“不合格”或“”。我喜欢做的是计算有多少用户将项目 1 分类为“合格”,有多少用户将项目 1 分类为“不合格”以及“不合格”。因此,如果 3 个用户将项目 1 分类为“合格”,2 个用户将项目 1 分类为“不合格”合格”,我可以说第 1 项是“合格”。
// count Qualified And Item One
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:"Qualified"}}}});
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:"Not Qualified"}}}});
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:""}}}});
我有 2 个模型,一个称为 User,另一个称为 Item。项目数组分配给每个用户(每个用户有 5 个项目)。通过每个用户的会话,用户可以将项目分类为合格或不合格或其中 none 个。这是模型:
const ItemSchema = new Schema({
title: {
type: String,
},
classification: {
type: String,
}
});
//Create the User Schema
const UserSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
items: [ItemSchema],
});
UserSchema.pre("save", function (next) {
this.items = [];
this.items.push({
title: "Item 1",
classification: ""
});
this.items.push({
title: "Item 2",
classification: ""
});
this.items.push({
title: "Item 3",
classification: ""
});
next();
});
module.exports = User = mongoose.model("users", UserSchema);
如您所见,用户的项目具有分类 属性,可以在其中写入“合格”或“不合格”或“”。我喜欢做的是计算有多少用户将项目 1 分类为“合格”,有多少用户将项目 1 分类为“不合格”以及“不合格”。因此,如果 3 个用户将项目 1 分类为“合格”,2 个用户将项目 1 分类为“不合格”合格”,我可以说第 1 项是“合格”。
// count Qualified And Item One
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:"Qualified"}}}});
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:"Not Qualified"}}}});
const res = await User.count({items:{ $elemMatch: { title: "Item 1",classification:""}}}});