0

So Currently the setup I have shows all the results from the users which is great but I only want to get the array called visits which the users hold.

This is how I have it set up so far:

getClicks() {
    this.http
      .get<{ message: string; users: any }>(
        BACKEND_URL_Analytics + '/user-clicks'
      )
      .pipe(
        map(data => {
          return data.users.map(user => {
            console.log(user);
            return {
              _id: user._id,
          *** visits: [user.visitCount] ****
            };
          });
        })
      )
      .subscribe(
        result => {
          this.userAnalytics = result;
          this.userAnalyticsUpdate.next([...this.userAnalytics]);
        },
        error => {
          console.log(error);
        }
      );
 }

These is my database structure:

const mongoose = require('mongoose');
const uniqueVal = require('mongoose-unique-validator');
const Schema = mongoose.Schema;

const visitsSchema = new Schema ({
  postId: {
    type: String
  },
  visitCount: {
    type: Number,
    default: 1
  }
})

const userSchema = mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  role: {
    type: String,
    required: true
  },
  answers: {
    type: String
  },
  visits: [visitsSchema]
});

userSchema.plugin(uniqueVal);

module.exports = mongoose.model('User', userSchema);

My aim is to get the user Id which is automatically created by mongoose, as _ID which is fairly easy to do. But then I need to access the visits: [visitsSchema].

This is the console.log result from console.log(user); :

{_id: "5b3f839e6633e59b673b4a4e", email: "[email protected]", password: "$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC", role: "admin", visits: Array(2), …}
email:"[email protected]"
password:"$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC"
role:"admin"
visits:Array(2)
0:{visitCount: 3, _id: "5b7c32015f015d5108002e88", postId: "5b5dbba4c67aad56df79f341"}
1:{visitCount: 1, _id: "5b7c32f72f457a517aaef23b", postId: "5b688fb0e90f608916e7548b"}

The visits array shown in the console.log contains the visitCount and the postID which I need to recover and send to the frontend. Any advice on how I can fix the map or the return values in order to get the right information. If getting the ID is too hard then I would accept just getting the visitCount and postID, So I can add that to a table and display it, thanks!

{
    "message": "Activities were fetched succesfully!",
    "users": [
        {
            "visits": [],
            "_id": "5b3f84246633e59b673b4a50",
            "email": "[email protected]",
            "password": "$2b$10$AZad.DdvPYHS4ttkLkQMyeA5wwe49JoSuJ4DvTO8xdp13gIlmF2Xy",
            "role": "teacher",
            "__v": 0
        },
        {
            "_id": "5b3f839e6633e59b673b4a4e",
            "email": "[email protected]",
            "password": "$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC",
            "role": "admin",
            "visits": [
                {
                    "visitCount": 3,
                    "_id": "5b7c32015f015d5108002e88",
                    "postId": "5b5dbba4c67aad56df79f341"
                },
                {
                    "visitCount": 1,
                    "_id": "5b7c32f72f457a517aaef23b",
                    "postId": "5b688fb0e90f608916e7548b"
                }
            ],
            "__v": 0
       },

Ontop is my postman request from the backend maybe this helps? Thanks

1 Answer 1

1

I don't get your question very well. But if what you want is to get all your users's data, you need populate(). For your case, this is how you should better do:

const visitsSchema = new Schema ({
       postId: {
           type: mongoose.Schema.Types.ObjectId, 
           ref: 'Post', // Reference to your Post model
      },
      visitCount: {
          type: Number,
          default: 1
      }
})

const userSchema = mongoose.Schema({
         email: {
             type: String,
             required: true,
             unique: true
         },
         password: {
             type: String,
             required: true
         },
         role: {
             type: String,
             required: true
         },
         answers: {
             type: String
         },
         visits: [{
             type: mongoose.Schema.Types.ObjectId, 
             ref: 'Visits', // Reference to your Visit model
         }]
});

Then I suppose you have your model like this:

userSchema.plugin(uniqueVal);

module.exports = mongoose.model('User', userSchema);
module.exports = mongoose.model('Post', postSchema);  // <- I suppose you have this
module.exports = mongoose.model('Visits', visitsSchema); // <- I suppose you have this

Now you can get all informations about your user for example like below:

User.findOne({email: '[email protected]'})
    .populate({
        path: 'visits',
        populate: { path: 'postId' }
    });

You can use populate() in multiple level.

Sign up to request clarification or add additional context in comments.

7 Comments

I'm getting the user's ID at the moment which is great, I just need the values inside the array, is there no other way to do it?
@Andrew Do you mean that you just need the array "visits" with all the informations about?
So as you see in my new edit the user's ID is getting pushed from the back to the frontend fine. But I can not figure out how to get into the visits array and get those two values the visitsCount and postID @Reactør
I have posted the postman request of the backend just to maybe help understand my question? I'm not the most experienced! Sorry
What you get is normal. You have to populate your visits data before returning them back as I post in my answer.
|

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.