0

I'm trying to map a URL using express routes to a specific value from every document I have in the database.

For example. In the Schema company.name would return a company name.

Is there a way to set the value of company.name to a unique URL?

The only way I thought of it was creating a loop or using mongoose's .find to iterate through the database and set it to

app.get('/' + name , function (req , res ) {
   res.render('company.jade');
});

However I'm not sure how to access the database collections from the routes file.

Using

const Company = require('.models/company');

Doesn't return the database so not sure what to do.

I'm not really hip on Mongoose or node.js yet. Really only need to do this one thing and the rest of the app is done in angular which I'm more familiar with.

Hopefully I made some sense here. I do have code for the app buts it's all basic code from app.js and routes.js. I can add it if it would be helpful.

3
  • Can you show me your MongoDB document for example, and be clear with what you want to be done? Commented Jul 17, 2017 at 1:57
  • Yeah I'll have to shorten it for the comment but essentially { company { 'name' : Microsoft} }, { company { 'name' : Apple } } and I want to generate url's /Microsoft /Apple etc. for each one. Sorry if that's not clear Commented Jul 17, 2017 at 2:03
  • This kinda thing should generally be done with a GET or POST request. Not knowing the way your server is set up makes this a bit hard to answer, though. Commented Jul 17, 2017 at 2:13

1 Answer 1

1

You are looking for Mongoose findOne query.

const Company = require('.models/company');

app.get('/:name', function(req, res){
Company.findOne({'company.name': req.params.name}) //company.name depends upon the schema you set.
 .then(function(company){
   if (company)
    return res.send({success: true, data: company}); //return company as an object containing the queried company document.

   else 
    return res.send({success: false, error: 'Company not found'});

 })
 .catch(function(err){
  if (err) res.send({success: false, error: err}); 
 });
});
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I was looking for, thanks. I was trying a bunch of things and it looks like I wasn't using the correct query, thanks

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.