我在节点js中编写查询,我的模式模型有3个对象(userid,tokenid,mediaid),我想找到某个用户id的令牌id并在另一个函数中使用它。
我的代码如下:
app.get('/registeruser/:userid', function(req, res){
var name = req.params.userid;
user.findOne({userid: name},function(err, users1){
if(!users1){
res.send('Error 404, user not found');
return res.status(404).send();
}
else{
var query = user.find({tokenid: 1});
query.where({userid: name});
query.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});
用户是我模型的名称。
我运行我的代码,并希望它返回令牌ID,但它返回以下内容:[]
这些在我的数据库中:
用户ID:“ hgfj1234”,
令牌ID:“ juiodkdn12345678”,
mediaid:['med10','med11']
当我写userid:'hgfj1234'时,它给了我这个:[]但我想要真正的tokenid。
如果有人可以帮助我,我真的很感激。
提前致谢。
最佳答案
您无需执行其他请求即可从mongodb获取记录。
这足以将findOne与复杂的属性一起使用。
尝试这个:
app.get('/registeruser/:userid', function(req, res) {
var query = {
userid: req.params.userid,
tokenid: {$exists: true, $not: {$size: 0}}
};
user
.findOne(query)
.exec(function(err, User) {
if(err) { // error happen,
console.error(err); // log error
return res.status(500).send({
success: false,
message: 'System error'
}); // respond with 500 status and send json response with success false and message. return will stop execution to go down
}
if(!User) { // response from database was empty or null
return res.status(404).send({
success: false,
message: 'User not found'
}); // respond with 404 status and send json response with success false and message. return will stop execution to go down
}
res.send({
success: true,
tokenid: User.tokenid
}); // and at last everything is ok, we return json response with success and tokenid in response
});
});
query
变量中的属性意味着请求mongodb向我们提供请求中定义的userid
且具有tokenid
且不是空字符串(非大小0)的文档。如果您仍然没有得到想要的结果,那么请检查数据库是否存在必要的文件。