2016-06-21 76 views
0

用戶的帳戶可以使用Comment Mongoose模型進行評論。 是否可以允許用戶在文本輸入中輸入username並生成所有與用戶相關的註釋?搜索Mongoose用戶

我一直在嘗試使用db.users.find({"name"),但我不知道如何將username從輸入字段傳遞到搜索。有什麼建議麼?

謝謝!評論模型如下。它將每個評論與用戶連接起來。

var commentSchema = new mongoose.Schema({ 
    body: String, 
    author: { 
     id: { 
      type: mongoose.Schema.Types.ObjectId, 
      ref: "User" 
     }, 
     username: String 

    } 
}) 
+0

你能告訴我們的代碼和dbstructure呢? – Shrabanee

+0

「生成所有與用戶相關的評論」是什麼意思?你想創建一個新的記錄,或者你想找到記錄的名字? – Shrabanee

+0

添加了上述模型。 Shrabanee我希望任何使用該網站的人都能夠查看用戶的評論。因此,「用戶1」可以通過在前端的輸入中輸入「用戶2」來搜索「用戶2」的評論。 – AndrewLeonardi

回答

1

你必須採取由其他用戶從text box進入user name發送到後端,像{uName : 'user2'}請求。

使用該請求附帶的對象中的值並在數據庫中查找。

類似下面將是後端代碼: -

var uName = req.params.uName 

var cursor = db.users.find({username : uName.toString()}); 

現在cursor會給你從user2從您的數據庫記錄。

0

前端

發送您查詢字符串GET請求到後端API

<form method="get" action="/comments/user" > 
    <input type="text" name="username" placeholder="username"> 
    <button type="submit">Search</button> 
</form> 

後端

寫一個API來處理GET請求貓鼬和查詢

var app = express(); 

var Comment = mongoose.model('Comment', commentSchema); 


app.get('/comments/user', function (req, res) { 

    var query=Comment.find(); 

    //get the Query String here 
    var filter=req.params.username; 

    if(filter.length>0){ 

     query.where({author.username:filter}); 

    } 

    query.exec(function (error, comment) { 
      //send the result back to front-end 
      res.json({ Comment: comment }); 
    }); 
});