简体   繁体   中英

Node && Mongodb findOne is not working

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"
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM