使用 Mongoose 搜索用户
Search for user with Mongoose
用户拥有帐户并可以使用 Comment
Mongoose 模型发表评论。
是否可以允许用户在文本输入中输入 username
并生成所有与用户相关的评论?
我一直在尝试使用 db.users.find({"name")
,但我不确定如何将 username
从输入字段传递到搜索。有什么建议么?
谢谢!评论模型如下。它将每个评论与用户联系起来。
var commentSchema = new mongoose.Schema({
body: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
})
您必须从 text box
获取另一个用户输入的 user name
并将其与 请求一起发送到后端 ,例如 {uName : 'user2'}
。
使用请求附带的对象的值并在您的数据库中查找。
后端代码如下所示:-
var uName = req.params.uName
var cursor = db.users.find({username : uName.toString()});
现在 cursor
将为您提供数据库中 user2
的记录。
前端
send your GET request with Query String to the Back-end API
<form method="get" action="/comments/user" >
<input type="text" name="username" placeholder="username">
<button type="submit">Search</button>
</form>
后端
write a API to deal with GET request and Mongoose Query
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 });
});
});
用户拥有帐户并可以使用 Comment
Mongoose 模型发表评论。
是否可以允许用户在文本输入中输入 username
并生成所有与用户相关的评论?
我一直在尝试使用 db.users.find({"name")
,但我不确定如何将 username
从输入字段传递到搜索。有什么建议么?
谢谢!评论模型如下。它将每个评论与用户联系起来。
var commentSchema = new mongoose.Schema({
body: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
})
您必须从 text box
获取另一个用户输入的 user name
并将其与 请求一起发送到后端 ,例如 {uName : 'user2'}
。
使用请求附带的对象的值并在您的数据库中查找。
后端代码如下所示:-
var uName = req.params.uName
var cursor = db.users.find({username : uName.toString()});
现在 cursor
将为您提供数据库中 user2
的记录。
前端
send your GET request with Query String to the Back-end API
<form method="get" action="/comments/user" >
<input type="text" name="username" placeholder="username">
<button type="submit">Search</button>
</form>
后端
write a API to deal with GET request and Mongoose Query
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 });
});
});