0

my backend

Can any one please tell me i have number of users in my mongodb. For example I have 3 users in my database, on that 2 users have reviews and the rest of the one user have no reviews. who have reviews i need to get only that users to frontend. My mongodb structure is:

_id:ObjectId("123") username:"xx" email:"xx" reviews:Array 0:Object

While i am using this below code i am getting all users to frontend.but i need only who have reviews, only that user i need to get to frontend.

//Getting reviews in Users to homepage
  userRouter.post('/getreviews', (req, res) => {
    Collections.user.find({}, {"reviews":1,"username":1},  function (err, result) {
    if (result) {
      //    console.log(result);
  res.status(200).json({users:result.map((user) => user.reviews)});
    } else {
   res.status(500).send("User Not Found with Details: " + JSON.stringify(user));
    }
    })
    });

1 Answer 1

2

You need to add condition in first {} to check whether reviews exists or not {"reviews": {$exists: true}}

//Getting reviews in Users to homepage

 userRouter.post('/getreviews', (req, res) => {
    Collections.user.find({"reviews": {$exists: true}}, {"reviews":1,"username":1},  function (err, result) {
    if (result) {
      //    console.log(result);
  res.status(200).json({users:result.map((user) => user.reviews)});
    } else {
   res.status(500).send("User Not Found with Details: " + JSON.stringify(user));
    }
    })
    });
Sign up to request clarification or add additional context in comments.

6 Comments

Reviews are getting in console. but if it is an empty array, i dont need to get that user. but now i am getting all reviews either it is empty or with data, showing in console.
In my database now there are three users. On that only one user have review rest of two users have no reviews. but console is showing three users. I need only Array(1) users. my console..-----> users: (3) [Array(1), Array(0), Array(0)]
you can try this connection.collection('user', function(error, collection) { if(error) { //console.log(error); return; } else { collection.find({"reviews": {$exists: true}}, {"reviews":1,"username":1}).toArray(function(error,results) { debug(results); }); } });
userRouter.post('/getreviews', (req, res) => { Collections('user', function(error, collection) { if(error) { //console.log(error); return; } else { collection.find({"reviews": {$exists: true}}, {"reviews":1,"username":1}).toArray(function(error,results) { debug(results); }); } }); }); ....I wrote like this.but it shows collection is not a function
connection.collection() connection object is your mongoDb coinnection object dont use collection directly
|

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.