Why am I only getting the content of one of my items?

I have a simple comments app which enables the user to enter a comment into the system via a form and these are then logged onto a list on the bottom of the page.

I wanted to modify it so that a user could click a comment once it is created and it would load up the associated content that goes with that comment.

My schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CommentSchema = new Schema({
    title: String,
    content: String,
    created: Date
});

module.exports = mongoose.model('Comment', CommentSchema);

My app.js routes:

app.use('/', routes);
app.use('/create', create);
app.use('/:title', show);

My show route:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);

router.get('/', function(req, res) {
    Comment.findOne(function(err, comment){
        console.log(comment.content)
    });
});

module.exports = router;

I have three comments in my system and saved in my database, each with unique contents, But whenever I click on a comment, no matter what it is. I am only getting the content that is associated with the first comment.

Why is this?

You'll have to provide a condition for .findOne() to retrieve a specific document:

Model.findOne(conditions, [fields], [options], [callback])

Without one, an empty condition is implied that matches every document in the collection:

Comment.findOne({}, function ...);

And, .findOne() simply retrieves the 1st of those that are matched.


With the :title parameter in the route for show and title property in the Schema, one possible condition would be:

Comment.findOne({ title: req.params.title }, function ...);

Though, if the titles aren't unique in order to find the "right" one, you'll have make the condition more specific. The _id or id would be the most distinct.

app.use('/:id', show);
Comment.findOne({ id: req.params.id }, function ...);

// or
Comment.findById(req.params.id, function ...);

Also adjusting any links and res.redirect()s to fill pass the id for :id.