Terrtiary
Terrtiary

Reputation: 191

How to create URL for every MongoDB document

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.

Upvotes: 0

Views: 798

Answers (1)

Animesh Singh
Animesh Singh

Reputation: 9322

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}); 
 });
});

Upvotes: 1

Related Questions