Taqiuddin Shokordey
Taqiuddin Shokordey

Reputation: 125

Get all data from Collection using mongodb and node js

I have a collection named Timetable. I Want to display all the data from Collection which consist only Classroom:6 bakti When I run console.log(). I only got an Object ID of the documents. I want to display all data from documents which have Classroom:6 bakti.

Data from Collection

{
    "_id" : ObjectId("5eaf124852a49d2cb4aa9d46"),
    "teacher" : "Siti Noor Khairani binti Afifudeen",
    "timeslot" : 1,
    "subject" : "Bahasa Melayu",
    "classroom" : "6 bakti",
    "year" : "2020",
    "__v" : 0
}

{
    "_id" : ObjectId("5eaf12a252a49d2cb4aa9d47"),
    "teacher" : "Siti Noor Khairani binti Afifudeen",
    "timeslot" : 2,
    "subject" : "Bahasa Inggeris",
    "classroom" : "6 Usaha",
    "year" : "2020",
    "__v" : 0
}
{
    "_id" : ObjectId("5eafd9285015e9001756d568"),
    "teacher" : "Siti Noor Khairani binti Afifudeen",
    "timeslot" : 2,
    "subject" : "Bahasa Melayu",
    "classroom" : "6 bakti",
    "year" : "2020",
    "__v" : 0
}

This is my Route file

i get url parameter using classroom.

router.get('/timetable_class/view/:id',mid, function(req,res){
  Timetable.find({classroom:req.params.id},{year:currentYear},function(err,timetable){
    if (err) throw err;
    console.log(currentYear);
    console.log(timetable, "hai");
    res.render('admin_content/view_timetable_class',{'timetable':timetable});
  });
});

View File

<H1><FONT COLOR="DARKCYAN"><CENTER><%= timetable %></FONT></H1>
       <table border="2" cellspacing="3" align="center">
          <tr>
          <td align="center">
              <td><%= timetable.classroom %>  
               <td><%= timetable.subject %>                                
      </td>

</tr>

Upvotes: 1

Views: 1186

Answers (2)

Vishal Tyagi
Vishal Tyagi

Reputation: 187

You have find with multiple conditions. For ex db.collection.find(query, projection) find takes a query and projection as a parameter. In your case you are passing {classroom: req.params.id} as query and {year: currentYear} as Projection which is wrong. You are using find with multiple conditions therefore you have to pass the condition as one argument.

In your case you are doing

 TimeTable.find({classroom:req.params.id}, {year:currentYear})

instead you should do find with

 TimeTable.find({classroom: req.params.id, year: currentYear})

Upvotes: 1

Mykhaylo Gusak
Mykhaylo Gusak

Reputation: 116

Try this $and operator: {$and:[{},{}]}

const currentYear = new Date().getFullYear()

Timetable.find({$and:[{classroom:req.params.id},{year:currentYear}]},function(err,timetable){
    if (err) throw err;
    console.log(currentYear);
    console.log(timetable, "hai");
    res.render('admin_content/view_timetable_class',{'timetable':timetable});
  });

Upvotes: 0

Related Questions