skip to Main Content

I have a project mongoose schema that contains the title and description of each project, and a ticket mongoose schema that also contains the title of the project the ticket is relevant to as well as the name of the user that the ticket is assigned to. Each individual project will be displayed on a post.ejs page, and I want to display the names of users who have been assigned tickets relating to that particular project.

Here is the get request so for the post.ejs page:

app.get("/posts/:postId", isLoggedIn, function(req, res) {
  const requestedPostId = req.params.postId;
  ProjectDetails.findOne({_id: requestedPostId}, function(err, post) {
    const tickets = TicketDetails.find({project: post.title});
    console.log(tickets);
    res.render("post", {title: post.title, content: post.content});
  });
});

I’m first querying the project database to find the project, then I’m querying the ticket database for all tickets related to the project, but when i console.log tickets I get an output like this:

output from console.log(tickets)

2

Answers


  1. You are receiving cursor
    You need to convert it to array

    const tickets = TicketDetails.find({project: post.title}).toArray();
    

    or

    const tickets = TicketDetails.find({project: post.title}).fetch();
    

    or

    const tickets = TicketDetails.find({project: post.title}).lean();
    
    Login or Signup to reply.
  2. As you mentioned in your query and console of tickets, it’s returning promise, and the default promise is pending. You need to resolve that promise. Use async-await or then-catch to resolve that promise. So your project query will be like this:

    with async-await:

    ProjectDetails.findOne({_id: requestedPostId}, async function(err, post) {
       const tickets = await TicketDetails.find({project: post.title});
       console.log(tickets);
       res.render("post", {title: post.title, content: post.content});
     })
    

    with then-catch:

    ProjectDetails.findOne({_id: requestedPostId}, function(err, post) {
        const tickets = TicketDetails.find({project: post.title}).then((resp) => return resp);
        console.log(tickets);
        res.render("post", {title: post.title, content: post.content});
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search