节点&& Mongodb findOne无法正常工作

时间:2017-11-22 12:16:41

标签: node.js mongodb express

无法读取属性'标题'无效!!!显示在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 个答案:

答案 0 :(得分:-1)

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

Book = mongoose.model('Book')

并像这样查询

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

当然,您必须确保标题是唯一的。