简体   繁体   English

猫鼬(mongodb)返回boolean query.exec吗?

[英]mongoose (mongodb) return boolean query.exec?

I try to make a library for use in node.js with mongoose (mongoDB). 我尝试使用mongoose(mongoDB)创建一个可在node.js中使用的库。 In my library, I want simply check if a user is_admin (group admin) or not. 在我的库中,我只想检查用户is_admin(组admin)是否存在。

Here is my model : 这是我的模特:

var mongoose = require('mongoose');

module.exports = mongoose.model('UsersGroups',{
    user_id: String,
    group_id: String
});

Here is my library : 这是我的图书馆:

var UsersGroups = require('../models/users_groups');

is_admin = function(userid)
{
    console.log('USERID : '+userid);
    var query = UsersGroups.find({'user_id': userid});
    query.select('user_id');
    query.where('group_id').equals('54d2264ed9b0eb887b7d7638');
    return query.exec();
}

module.exports = is_admin;

I want to the query return true or false . 我想查询返回truefalse

I call the library like this : 我这样称呼图书馆:

var is_admin = require('../library/mylib.js');

...

if (is_admin(group.user_id))
{
  console.log('IS_ADMIN');
}
else
{
 console.log('NOT_ADMIN');
}

Someone can coach me for this? 有人可以为此指导我吗?

query.exec() return Promise not Boolean Using mongoose Schema and Model will give more nice feature; query.exec()返回Promise not Boolean使用猫鼬的Schema和Model将提供更多不错的功能;

Example User Model 用户模型示例

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: { type: String, required: true, trim: true }
    // set user types as enumeration
    type: { type: String, enum: ["admin", "user", "guest"], required: ture, default: 'user' }
});

var User = mongoose.model('User', UserSchema);

User.prototype.isAdmin = function(){
    return this.type === "admin";
}

module.exports = User;

On controller 在控制器上

var user = require('model/user');

user.findById("54d2264ed9b0eb887b7d7638", function(err, user){
    if(err) 
        return console.error(err.stack);

    if(!user) 
        return console.error("User not found!");

    if(!user.isAdmin())
        console.log("User is not admin");
    else
        console.log("User is admin");
});

If you want to check with user group, you can change isAdmin function as you want 如果要检查用户组,可以根据需要更改isAdmin函数

You can just run this query 您可以运行此查询

UsersGroups.find({'user_id': userid, 'group_id': '54d2264ed9b0eb887b7d7638'}).count().exec();

it will find the matching pair - return 1 if it exists which is truthy in javascript. 它将找到匹配的对-如果存在,则返回1,这在javascript中是正确的。 If it does not exist it will return 0 which is falsy so you will be able to use it inside if statements 如果不存在,它将返回0,这是虚假的,因此您可以在if语句中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM