[英]Find by id or username in mongo
我正在嘗試像這樣通過用戶名或_id進行查找
exports.getUser = function (req, res){
User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] })
.exec(function (err, collections) {
res.send(collections);
});
};
當我通過_id搜索但無法輸入用戶名時,它可以工作,因為它無法返回有效的OjectID。 我試着做這樣兩個獨立的查詢
exports.getUser = function (req, res){
User.findOne({username:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
};
但這會在用戶不存在時掛起,因為它從不發送響應。 由於節點是異步的,因此出現Error: Can't set headers after they are sent.
如果我加上
else
res.sendStatus(400);
到findById查詢。 我想不出任何其他方法來解決這個問題。我在MongoDB節點中嘗試了正則表達式來檢查objectid是否有效
exports.getUser = function (req, res){
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if(checkForHexRegExp.test(req.params.id)){
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
}
User.findOne({username:req.params.id}).exec(function (err, user) {
res.send(user);
});
};
而且我遇到了同樣的錯誤,因為它是異步的。 必須有一個比這更好的方法
很可能您的第一個查詢將無法正常工作,因為MongoDB期望_id
是一個ObjectId,而不是字符串( req.params.id
可能是字符串):
var ObjectId = require('mongoose').Types.ObjectId;
exports.getUser = function (req, res) {
var id = req.params.id;
var $or = [ { username : id } ];
// Does it look like an ObjectId? If so, convert it to one and
// add it to the list of OR operands.
if (ObjectId.isValid(id)) {
$or.push({ _id : ObjectId(id) });
}
User.find({ $or : $or }).exec(function (err, collections) {
// TODO: check for errors
res.send(collections);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.