【问题标题】:Mongoose: Finding a user in a collection and checking if this user's array contains x?Mongoose:在集合中查找用户并检查该用户的数组是否包含 x?
【发布时间】:2014-07-01 09:44:20
【问题描述】:

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

{
"__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”。 猫鼬如何做到这一点?

【问题讨论】:

    标签: javascript arrays mongodb mongoose


    【解决方案1】:

    这很容易做到。下面的代码详细描述了实现这一点必须做的事情。

    步骤:

    1. 获取猫鼬模块
    2. 连接到 mongo 并找到正确的数据库
    3. 为您的集合创建一个架构(在这种情况下仅限用户)
    4. 添加一个自定义方法,如果角色“mod”存在于数组中,则返回true。注意:mongo 集合没有结构,因此最好检查一下属性“roles”是否存在并且它是一个数组。
    5. 为创建的架构建模。
    6. 通过查找随机(一个)文档/用户来测试它,并检查它是否是版主。

    所以,这被编程为:

    //  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());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 2018-08-11
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      相关资源
      最近更新 更多