1

I am trying to search through all the comments and return all comments created by a specific user from my mongodb how ever when i try to search the array returned is empty.

I have tried :

Comment.find({author: {$elemMatch: {username: req.params.username}}}, (err, foundComments) => {
        // Code goes here
      });

The Mongoose Comment Schema:

const mongoose = require('mongoose');

const commentSchema = new mongoose.Schema({
  text: String,
  discussion:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
  }],
  createdAt: {
    type: Date,
    default: Date.now,
  },
  author: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
    username: 'String',
    avatar: {
      image: String,
      imageId: String,
    },
  },
  likes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }],
  dislikes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }],
});

module.exports = mongoose.model('Comment', commentSchema);

When I run it I am expecting foundComments to be an array [ array of comments ] but I just get an empty array [].

DittoGod
  • 37
  • 1
  • 1
  • 5

2 Answers2

2

Comment.find({"author.username":req.params.username});

RameshN
  • 510
  • 7
  • 14
0
Comment.find({"username": req.params.username},{"discussion":1,"_id":0})
vicky
  • 415
  • 2
  • 10