0
votes

Cannot read property 'title' of null !!! Showing While rendring the findone.ejs file.. But The first one in db is showing perfectly..

app.get('/books/:title', (req, res) => {
  db.collection("Book")
    .findOne({ 'title': req.params.title }, function(err, result) {
      if (err) throw err;

      res.render('findone.ejs', { Book: result});
    });
})

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

var BookSchema = new Schema({
    title: String,
    author: String,
    category: String
});

module.exports = mongoose.model('Book', BookSchema);

Mongo Database.

{
    "_id": {
        "$oid": "5a14a5edf6fe123247b890f3"
    },
    "title": "ttt",
    "author": "ttttt",
    "category": "tttttttttttt"
}

{
    "_id": {
        "$oid": "5a14a5f2f6fe123247b890f4"
    },
    "title": "tttt",
    "author": "ttttt",
    "category": "ttttttttttttttttttttttttttt"
}

{
    "_id": {
        "$oid": "5a154e4bff45fe2c9035f9da"
    },
    "title": "hello ",
    "author": "rabbani",
    "category": "how are you"
}
1
Then that means the query is not matching any documents or there are no documents in the collection with that specific title. When you log req.params.title before the query, what do you get? - chridam
it is showing the title i want to compare && that i am giving on the link. The first value of the database is showing with out any error .. - Rabbani_
Can you add your ''Book" model code - Akinjide
Also I see you're using es6 and es5, consistency matters, you should refactor that. - Akinjide
@akinjide I have update the code And have a look on my database schema. - Rabbani_

1 Answers

-3
votes

If you are using mongoose then you can import the schema like this

Book = mongoose.model('Book')

and query like this

Book.findOne({"title": title}, function(err, book) {
  //handle book
})

Of course you have to ensure that the title is unique.