2014-08-30 52 views
0

我有一个简单的评论应用程序,它可以让用户通过表单将注释输入到系统中,然后这些注释会被记录到页面底部的列表中。为什么我只能获取我的其中一件物品的内容?

我想对其进行修改,以便用户在创建注释后可以点击该注释,并加载与该注释一起使用的关联内容。

我的架构:

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; 

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

这是为什么?

回答

0

你必须提供一个condition for .findOne()检索特定的文件:

Model.findOne(条件,[场],[选项],[回调]

没有一个,暗示与空间condition匹配集合中的每个文档:

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

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


随着路由的:title参数show并在Schematitle属性,一种可能的情况是:

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

不过,如果title S IN顺序并不是唯一发现“正确”一个,你会使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

+0

谢谢,我现在已经改变了我的路线为: Comment.findOne({_id:req.params.id},功能(ERR,评论){ \t \t的console.log(comment.content) }); 但我现在在我的终端中出现错误,说'内容'是null的属性。 – Keva161 2014-08-30 21:07:32

+0

@ Keva161'comment'的'null'表示'condition'与任何文档都不匹配。检查是否发生错误。此外,确保与路由相关的所有内容都使用'id'而不是'title' - ':id'在路由中,任何指向它的'href's和'redirect'都使用路径中的'id' ,'req.params.id'的值是[数字](http://docs.mongodb.org/manual/reference/object-id/)。 – 2014-08-30 21:22:22

+0

如果我尝试从我的app.js注销req.params.id,它会按预期提供值。但是,如果我尝试通过show route注销它,我只会收到一条未定义的消息。 – Keva161 2014-08-30 21:36:00

相关问题