【问题标题】:Why am I only getting the content of one of my items?为什么我只能获得其中一件物品的内容?
【发布时间】:2014-10-24 13:02:27
【问题描述】:

我有一个简单的 cmets 应用程序,它允许用户通过表单在系统中输入评论,然后这些评论会登录到页面底部的列表中。

我想对其进行修改,以便用户可以在创建评论后单击它并加载与该评论相关的相关内容。

我的架构:

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

var CommentSchema = new Schema({
    title: String,
    content: String,
    created: Date
});

module.exports = mongoose.model('Comment', CommentSchema);

我的 app.js 路由:

app.use('/', routes);
app.use('/create', create);
app.use('/:title', show);

我的表演路线:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);

router.get('/', function(req, res) {
    Comment.findOne(function(err, comment){
        console.log(comment.content)
    });
});

module.exports = router;

我的系统中有三个 cmets 并保存在我的数据库中,每个都有独特的内容,但是每当我点击评论时,不管它是什么。我只得到与第一条评论相关的内容。

这是为什么?

【问题讨论】:

    标签: node.js express routes mongoose


    【解决方案1】:

    您必须提供condition for .findOne() 才能检索特定文档:

    Model.findOne(条件、[字段]、[选项]、[回调])

    如果没有,则暗示一个空的condition 匹配集合中的每个文档:

    Comment.findOne({}, function ...);
    

    而且,.findOne() 只是检索匹配的第一个。


    使用show 的路由中的:title 参数和Schema 中的title 属性,一种可能的情况是:

    Comment.findOne({ title: req.params.title }, function ...);
    

    不过,如果 titles 不是唯一的以找到“正确的”之一,您将需要使 condition 更具体。 _idid 将是最独特的。

    app.use('/:id', show);
    
    Comment.findOne({ id: req.params.id }, function ...);
    
    // or
    Comment.findById(req.params.id, function ...);
    

    同时调整任何链接和res.redirect()s 以填充传递id:id

    【讨论】:

    • 谢谢,我现在改变了我的阅读路线:Comment.findOne({ _id: req.params.id}, function(err, comment){ console.log(comment.content) } );但是我现在在我的终端中收到一个错误,说“内容”是 null 的属性。
    • @Keva161 null for comment 表示 condition 不匹配任何文档。检查是否出现err。另外,确保与路由相关的所有内容都使用id 而不是title——:id 在路由中,任何指向它的hrefs 和redirects 在路径中使用id,并且req.params.id 有一个值that's numeric
    • 如果我尝试从 app.js 中注销 req.params.id,它会提供预期的值。但是,如果我尝试通过我的显示路线将其注销,我只会收到一条未定义的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2014-01-09
    相关资源
    最近更新 更多