簡體   English   中英

我似乎無法理解貓鼬的“ findOne”

[英]I can't seem to understand Mongoose's “findOne”

好的,所以我有此功能可以從mongodb db獲取ID為id的博客文章。

 exports.blogPostFirst = function(req, res, next) {

     BlogPost.findOne({    
         _id: '1'
     }, function(err, e) {
         if (err) {
             return next(err);
         } else {
             req.content = e;
             next();
         }
     });

     res.render('blogPage', {
         title: req.content.title,
         content: req.content.html_content
     })
 };

現在由於某種原因, _id : '1'部分不起作用,_id字段為字符串。

當我改為給_id參數一個元素的from形式的值時,形成一條路線,例如,我的路線中有“ route :: param”

並且我在第4個參數'id'上方提供了該函數,並將其作為“ param”參數傳遞,但效果很好,但是我對如何手動設置“ _id”字段感到困惑。

BlogPost對象如下:

var BlogPost = require('mongoose').model('Post');

貓鼬的模式是:

Schema = mongoose.Schema;

var PostSchema = new Schema({
    title: String,
    html_content: String,
    _id: String,
});

mongoose.model('Post', PostSchema);

好的,因此,經過一秒鍾的清晰思考,我看到了我的問題。 當我寫:

BlogPost.findOne({    
     _id: '1'
 }, function(err, e) {
     if (err) {
         return next(err);
     } else {
         req.content = e;
         next();
     }
 });

我將請求的.content參數設置為等於“ e”(我的findOne查詢的結果),但是在findOne函數“完成”之后,req.content不會保持其值為req.content ,而是僅存在於該函數的環境中,因此我應該這樣調用該函數:

exports.blogPostFirst = function(req, res, next) {

     BlogPost.findOne({    
         _id: '1'
     }, function(err, e) {
         if (err) {
             return next(err);
         } else {
             req.content = e;
             next();
              res.render('blogPage', {
         title: req.content.title,
         content: req.content.html_content
     })
         }
     }); 
 };

令我感到困惑的是為什么當我將其與從URL傳遞的參數一起使用時,它根本無法工作...或者也許我找到了修復程序,但是我的修復理由很糟糕。 無論如何,我有我的答案,但是我無法刪除它,所以我將其留在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM