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”。
猫鼬怎么能做到这一点呢?这很容易做到。下面的代码详细描述了要实现这一点必须执行的操作 步骤:
// 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());
});