alireza
alireza

Reputation: 557

Node.js Mongoose list all document by field

I have simple app , its blog.

it's my schema in mongoose

 var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String
});
var Blog = mongoose.model('Blog', blogSchema);

i want show all blog post its my rout:

app.get('/', function(req, res, next) {
  Blog.find(function (err, post) {
    res.render('default',{data: post});
  });
});

until now everything work fine , its show list of my post in json style.

when i want show just titles i change {data: post} to {data: post.title} its dont show anything.

Upvotes: 0

Views: 661

Answers (1)

Tom Hallam
Tom Hallam

Reputation: 1950

You are getting a collection of posts back from your Blog collection. That's fine - however, it sounds like what you are looking for is displaying a single item.

You'll either need to refer to it like this (which will return the title of the first post):

app.get('/', function(req, res, next) {
  Blog.find(function (err, posts) {
    res.render('default',{data: posts[0].title});
  });
});

Or you'll need to create a new endpoint to get a single item:

app.get('/', function(req, res, next) {
  Blog.find(function (err, posts) {
    res.render('default',{data: posts});
  });
});

app.get('/post/:postId', function(req, res, next) {
  Blog.findOne({_id: req.param('postId')}, function (err, post) {
    res.render('default',{data: post.title});
  });
});

The difference with the bottom one is I'm creating a named route that accepts a parameter called postId, which I then pass into the Mongoose method, and in turn the database tries to find a post with _id = :postId. So if I call:

http://example.com/post/123 - the :postId parameter will be equal to 123.

You access request parameters using the following syntax in Express:

req.param('nameOfParam'). In this example I used req.param('postId'). The : will automatically be stripped for you.

The second example also uses findOne(), which only retrieves you one row based on a set of criteria (in this case, find me one with an _id = :postId), rather than a collection.

Edit: to answer your question about getting the last ten posts, you can use the same code you had before, but with a little change:

app.get('/', function(req, res, next) {
  Blog.find().limit(10).sort('id').exec(function (err, posts) {
    res.render('default',{data: posts});
  });
});

You can then render the titles in your view file. If you wanted data to just contain the post titles, you can do this:

app.get('/', function(req, res, next) {
  Blog.find().limit(10).sort('id').exec(function (err, posts) {

    var postTitles = posts.map(function(post) { return post.title; });
    res.render('default',{lastPostTitles: postTitles});

  });
});

See the documentation on Mongoose Queries for more information.

Hopefully that helps.

Upvotes: 2

Related Questions