Node.js 为什么我只得到我的一个项目的内容?

Node.js 为什么我只得到我的一个项目的内容?,node.js,express,routes,mongoose,Node.js,Express,Routes,Mongoose,我有一个简单的评论应用程序,用户可以通过表单将评论输入系统,然后登录到页面底部的列表中 我想对其进行修改,以便用户可以在创建注释后单击该注释,并加载与该注释相关的内容 我的模式: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CommentSchema = new Schema({ title: String, content: String, created: Date })

我有一个简单的评论应用程序,用户可以通过表单将评论输入系统,然后登录到页面底部的列表中

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

我的模式:

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

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

module.exports = mongoose.model('Comment', CommentSchema);
My 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;
我的系统中有三条注释,并保存在数据库中,每一条注释都有唯一的内容,但每当我点击注释时,无论它是什么。我只得到与第一条评论相关的内容

这是为什么?

您必须提供检索特定文档的方法:

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

如果没有,则表示与集合中的每个文档匹配的条件为空:

Comment.findOne({}, function ...);
而且,
.findOne()
只检索匹配的第一个


对于
模式中的
show
title
属性的路由中的
:title
参数,一种可能的情况是:

Comment.findOne({ title: req.params.title }, function ...);
但是,如果为了找到“正确”的标题,标题不是唯一的,则必须使条件更加具体。or将是最明显的

app.use('/:id', show);

还调整了所有链接和
res.redirect()
s以填充
:id

id
,谢谢,我现在将路径改为:Comment.findOne({u id:req.params.id},function(err,Comment){console.log(Comment.content)});但是我现在在终端中收到一个错误,说“内容”是null属性。@Keva161 a
null
for
comment
表示
条件与任何文档都不匹配。检查是否出现
错误
。另外,确保与路由相关的所有内容都使用
id
而不是
title
--
:id
在路由中,任何
href
s和
重定向
s指向它的都使用路径中的
id
,并且
req.params.id
有一个值。如果我试图从我的app.js注销req.params.id,它提供了预期的值。然而,如果我试图通过我的表演路线注销它,我只会收到一条未定义的消息。
Comment.findOne({ id: req.params.id }, function ...);

// or
Comment.findById(req.params.id, function ...);