0

I have 2 models one is called User and the other Item. An array of items is assigned to each User(each user has 5 items). Through each user's session, the user can classify the items to Qualified or Not Qualified or none of them. Here is the Models:

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);

As you can see the user's items has classification property which can be written "Qualified" or "Not Qualified" or "" in it. What I like to do is to count how many users classify Item 1 as "Qualified" and how many as "Not Qualified" & how many as "".So if 3 users classified Item 1 as "Qualified" and 2 users as "Not Qualified", I can say Item 1 is "Qualified".

1 Answer 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:""}}}});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you,it worked! But in case I would have 20 items.Is there any way to loop through all the items or I should do for all of them separately like above?
Querying database in loop is not a good choice also aggregation for multiple stage can be complex, as a alternate way you can use below code const docs = await User.count().select({results:1}); const aggregate = {}; for(document of docs ){ if(!aggregate[document.item]){ aggregate[document.item] = {} } if(!aggregate[document.item][document.classification]){ aggregate[document.item][document.classification] = 0; } aggregate[document.item][document.classification] ++; } due to character limit i can't post full code in comment, handle classification empty case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.