2014-08-30 51 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

相關問題