FFXX
FFXX

Reputation: 115

How to concatenate the array in a sub-schema of a schema using mongodb?

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 will answer some questions and the answers will be stored in an array. Here is the Models:

const ItemSchema = new Schema({
    title: {
        type: String,
    },
    answers: {
        type: Array,
    },
});
//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",
    answers: ["", "", ""]
  });
  this.items.push({
    title: "Item 2",
    answers: ["", "", ""]
  });
  this.items.push({
    title: "Item 3",
    answers: ["", "", ""]
  });
  this.items.push({
        title: "Item 4",
        answers: ["", "", ""]
      });
  this.items.push({
        title: "Item 5",
        answers: ["", "", ""]
      });
  next();
});
module.exports = User = mongoose.model("users", UserSchema);

My question is if 20 Users has logged in and answered the questions, how I can concatenate all of the answers together in an array. So as a response I'll have the following :

[
    {
        "title": "Item 1",
        "allAnswers":["user1-answer1","user1-answer2","user1-answer3","user2-answer2","user2-answer2",...]
    },
    {
        "title": "Item 2",
        "allAnswers":["user1-answer1","user1-answer2","user1-answer3","user2-answer2","user2-answer2",...]
    },
    ...
]

Upvotes: 2

Views: 57

Answers (1)

DTan13
DTan13

Reputation: 438

You can define a static method on UserSchema to access all users and concatenate the answers in a array.

as follows

UserSchema.statics.ItemsToArray = function(){
    let users = this.Find()
    // Further actions on Users and their responses
}

Upvotes: 1

Related Questions