首页 文章

Node && Mongodb findOne无效

提问于
浏览
2

无法读取null的属性'title'!显示在rendring findone.ejs文件时..但db中的第一个显示完美..

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

数据库架构: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数据库 .

{
    "_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 回答

  • -1

    如果您使用的是mongoose,那么您可以像这样导入架构

    Book = mongoose.model('Book')
    

    和这样的查询

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

    当然,您必须确保 Headers 是唯一的 .

相关问题