Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose:在集合中查找用户并检查此用户是否';s数组包含x?_Javascript_Arrays_Mongodb_Mongoose - Fatal编程技术网

Javascript Mongoose:在集合中查找用户并检查此用户是否';s数组包含x?

Javascript Mongoose:在集合中查找用户并检查此用户是否';s数组包含x?,javascript,arrays,mongodb,mongoose,Javascript,Arrays,Mongodb,Mongoose,我有一个名为“用户”的集合,其中典型的用户条目如下所示: { "__v" : 0, "_id" : ObjectId("536d1ac80bdc7e680f3436c0"), "joinDate" : ISODate("2014-05-09T18:13:28.079Z"), "lastActiveDate" : ISODate("2014-05-09T18:13:48.918Z"), "lastSocketId" : null, "password" : "Johndoe6", "roles"

我有一个名为“用户”的集合,其中典型的用户条目如下所示:

{
"__v" : 0,
"_id" : ObjectId("536d1ac80bdc7e680f3436c0"),
"joinDate" : ISODate("2014-05-09T18:13:28.079Z"),
"lastActiveDate" : ISODate("2014-05-09T18:13:48.918Z"),
"lastSocketId" : null,
"password" : "Johndoe6",
"roles" : ['mod'], // I want this to be checked
"username" : "johndoe6"
}
我想创建一个if函数来查找用户变量targetuser,并检查他的“roles”数组是否包含“mod”。
猫鼬怎么能做到这一点呢?

这很容易做到。下面的代码详细描述了要实现这一点必须执行的操作

步骤:

  • 获取猫鼬模块
  • 连接到mongo并找到正确的数据库
  • 创建集合的架构(在本例中,仅限用户)
  • 添加一个自定义方法,如果数组中存在角色“mod”,该方法将返回true。注意:mongo集合没有结构,因此最好运行一个检查属性“roles”是否存在并且它是否是一个数组
  • 对创建的模式进行建模
  • 通过查找随机(一)个文档/用户来测试它,并检查它是否是版主
  • 因此,这被编程为:

    //  get mongoose.
    var mongoose = require('mongoose');
    
    //  connect to your local pc on database myDB.
    mongoose.connect('mongodb://localhost:27017/myDB');
    
    //  your userschema.
    var schema = new mongoose.Schema({
      joinDate      : {type:Date, default:Date.now},
      lastActiveDate: Date,
      lastSocketId  : String,
      username      : String,
      password      : String,
      roles         : Array
    });
    
    //  attach custom method.
    schema.methods.isModerator = function() {
      //  if array roles has text 'mod' then it's true.
      return (this.roles.indexOf('mod')>-1);
    };
    
    //  model that schema giving the name 'users'.
    var model = mongoose.model('users', schema);
    
    //  find any user.
    model.findOne({}, function(err, user)
    {
      //  if there are no errors and we found an user.
      // log that result.
      if (!err && user) console.log(user.isModerator());
    });