【问题标题】:Node && Mongodb findOne is not working节点 && Mongodb findOne 不工作
【发布时间】:2018-05-06 04:20:55
【问题描述】:

无法读取 null 的属性“标题”!!!在渲染 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 猫鼬 = 要求('猫鼬'); 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"
}

【问题讨论】:

  • 那么这意味着查询不匹配任何文档,或者集合中没有具有该特定标题的文档。当你在查询前登录req.params.title,你会得到什么?
  • 它显示了我想比较的标题 && 我在链接上给出的。数据库的第一个值显示没有任何错误..
  • 你能添加你的''Book'型号代码
  • 另外我看到你使用的是 es6 和 es5,一致性很重要,你应该重构它。
  • @akinjide 我已更新代码并查看我的数据库架构。

标签: node.js mongodb express


【解决方案1】:

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

Book = mongoose.model('Book')

像这样查询

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

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

【讨论】:

  • @rabbani 的评论是 Cannot read property 'title' of null !!! 我确定他正在导入模型
  • 那不是说req.params 为空吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多