【发布时间】:2014-06-30 15:13:03
【问题描述】:
基本上,我正在尝试在 Shotgun npm 模块中为 Node.js 创建一个命令,该命令在数据库中找到一个用户,如果他存在则禁止他。
这是一个示例用户条目(用户存储在一个名为“用户”的集合中):
{
"__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" : [], //the 'banned' will goe here, ex. ['banned']
"username" : "johndoe6"
}
这是我的命令js代码:
exports.roles = 'mod, admin'; //this command is only to be used by users who are admins or mods
exports.description = "Sets the specified user's ban status."; //info for help menu
exports.usage = "<USER>"; //also more help into
exports.options = { //start of username prompt
username: { //name of the option
required: true,
prompt: "Please enter a user username to edit.",
noName: true,
hidden: true,
validate: /^[a-z0-9_-]+$/i,
},
confirm: { //this is a yes/no prompt for adding to the array
description: "Confirms user ban.",
validate: function (confirm, shell, options) {
var confirmRegex = /^y(es)?|true$/i;
options.confirm = confirmRegex.test(confirm);
return options.confirm ? true : "User ban canceled.";
}
}
};
exports.invoke = function (shell, options) { //shotgun thing
shell.db.users.find({ "username" : options.username }); //find username based on what was plugged in for 'options.username' which was our prompt
if (err) return shell.error(err);
if (!user) return shell.error("No user with username {{0}} exists.".format(options.username));
shell.getCurrentUser(function (currentUser) {
// If user did not supply confirm already then set the CLI text to edit and prompt for user confirm.
if (options.username.isModOrAdmin()){ //check if a user has 'mod' or 'admin' in array 'roles'
return shell.error("You cannot ban other mods or admins".format(options.username))
}
if (!options.confirm) {
shell.log("Modify user {{0}} confirm.".format(options.username));
shell.setPrompt('confirm', 'editUser', options);
}
else {
// If we have user confirm then modify the user.
user.username = options.confirm;
if (err) return shell.error(err);
shell.db.users.update({ "username" : options.username }, {$addToSet: {roles: "banned"}}); //go into the database, find the user we typed into the prompt and add a 'banned' into its 'roles' array
shell.log("User {{0}} banned successfully.".format(options.username)); //notify command user that ban happened
};
});
};
正如您所看到的,这是基本要点,我只是在查找用户以检查他是否存在以及修改他的数组方面遇到了问题。如何更改此代码,以便使用输入用户名提示的文本在数据库中搜索我的数据库的“用户”集合中的现有用户,然后将“禁止”添加到他的“角色”数组中?
编辑:我现在意识到我只需要将它们转换为 Mongoose 我把第一部分记下来了,我想, shell.db.User.findOne({ username: options.username }, function (err, user) { 这会根据提示找到用户,当然是options.username
【问题讨论】:
标签: javascript arrays node.js mongodb mongoose