我正在尝试在MongoDB上维护一个用户表,该表包含从Slack通道中提取的内容,我们可以从Slack API中进行访问。目前,我尝试检查每次加载服务器时是否存在该频道的任何新成员,如果有,请创建一个新用户。
以下是当前告诉我所有用户已经存在但我的用户表目前只有1个条目的脚本,它应该还创建了6个用户。
slack_data
是对松弛api的调用结果。
const Users = require('../models/users');
const _ = require('lodash');
function Database(){
}
Database.prototype.integration = function(slack_data){
var jsonLength = Object.keys(slack_data).length;
var i;
for (i = 0; i <= jsonLength; i++) {
if (Users.find({slack_id: slack_data.members[i].id}) != 'undefined'){
console.log('User already exists');
}
else{
Users.create({
name: slack_data.members[i].real_name,
slack_id: slack_data.members[i].id,
slack_image: slack_data.members[i].profile.image_192,
slack_image_48: slack_data.members[i].profile.image_48,
slack_image_512: slack_data.members[i].profile.image_512
})
console.log(slack_data.members[i].real_name, " created");
}
}
}
module.exports = Database;
我得到的实际console.log输出是:
undefined
User already exists
User already exists
User already exists
User already exists
User already exists
这又有点奇怪,因为Slack API中有7条用户记录。
松弛的api结构如下:
{
ok: true,
members: [
{
id: "USLACKBOT",
team_id: "TCW7",
name: "slackbot",
deleted: false,
color: "757575",
real_name: "slackbot",
tz: null,
tz_label: "Pacific Daylight Time",
tz_offset: -25200,
profile: {
title: "",
phone: "",
skype: "",
real_name: "slackbot",
real_name_normalized: "slackbot",
display_name: "slackbot",
display_name_normalized: "slackbot",
fields: null,
status_text: "",
status_emoji: "",
status_expiration: 0,
avatar_hash: "sv1444671949",
always_active: true,
first_name: "slackbot",
last_name: "",
image_24: "https://a.slack-edge.com/0180/img/slackbot_24.png",
image_32: "https://a.slack-edge.com/7f1a0/plugins/slackbot/assets/service_32.png",
image_48: "https://a.slack-edge.com/7f1a0/plugins/slackbot/assets/service_48.png",
image_72: "https://a.slack-edge.com/0180/img/slackbot_72.png",
image_192: "https://a.slack-edge.com/66f9/img/slackbot_192.png",
image_512: "https://a.slack-edge.com/1801/img/slackbot_512.png",
status_text_canonical: "",
team: "TCW7"
},
is_admin: false,
is_owner: false,
is_primary_owner: false,
is_restricted: false,
is_ultra_restricted: false,
is_bot: false,
is_app_user: false,
updated: 0
},
您能帮助我找出问题所在并建议我如何执行所需的用户创建吗?
使用“等待”选项,我的代码现在如下所示:
const Users = require('../models/users');
const _ = require('lodash');
function Database(){
}
Database.prototype.integration = async (slack_data) => {
let newUsers = [];
for (let i = 0; i < slack_data.members.length; i++) {
const user = await Users.findOne({slack_id: slack_data.members[i].id});
if (!user || typeof user.slack_id === 'undefined') {
newUsers.push({
name: slack_data.members[i].real_name,
slack_id: slack_data.members[i].id,
slack_image: slack_data.members[i].profile.image_192,
slack_image_48: slack_data.members[i].profile.image_48,
slack_image_512: slack_data.members[i].profile.image_512
});
};
}
const newSlackUsers = await Users.insertMany(newUsers);
console.log('New users created ', newSlackUsers);
}
module.exports = Database;
答案 0 :(得分:1)
find()
方法是异步的,由于它们的异步特性,无法得知这些函数何时完成,或者将它们放入for循环时,它们以什么顺序完成。
有几种处理方法。您可以使用在exec()
或findOne()
方法上调用find()
方法时返回的默认Promise。
您还可以包含async / await,其中async / await可以阻止async函数,因此可以阻塞数组迭代,直到await响应为止。
另一种选择是使用立即调用的匿名函数,以确保使用正确的索引变量值来调用异步函数。
让我们通过示例探索每个选项。
使用承诺
const _ = require('lodash');
Database.prototype.integration = (slack_data) => {
let userPromises = [];
for (let i = 0; i < slack_data.members.length; i++) {
const user = User.findOne({slack_id: slack_data.members[i].id}).lean().exec();
userPromises.push(user);
}
Promise.all(userPromises).then(users => {
const memberIds = slack_data.members.map(s => s.id);
const slackIds = users.map(u => u.slack_id);
const newUserIds = _.difference(slackIds, memberIds);
const newUsers = newUserIds.map(id => {
const member = _.find(slack_data.members, ['id', id]);
return {
name: member.real_name,
slack_id: member.id,
slack_image: member.profile.image_192,
slack_image_48: member.profile.image_48,
slack_image_512: member.profile.image_512
}
);
return User.insertMany(newUsers);
}).then(newUsers => console.log('New users created ', newUsers));
}
使用异步/等待
Database.prototype.integration = async (slack_data) => {
let newUsers = [];
for (let i = 0; i < slack_data.members.length; i++) {
const user = await User.findOne({slack_id: slack_data.members[i].id}).lean().exec();
if (typeof user === 'undefined') {
newUsers.push({
name: slack_data.members[i].real_name,
slack_id: slack_data.members[i].id,
slack_image: slack_data.members[i].profile.image_192,
slack_image_48: slack_data.members[i].profile.image_48,
slack_image_512: slack_data.members[i].profile.image_512
});
};
}
const newSlackUsers = await User.insertMany(newUsers);
console.log('New users created ', newSlackUsers);
}
使用IIFE (立即调用功能表达式)
Database.prototype.integration = (slack_data) => {
let newUsers = [];
for (let i = 0; i < slack_data.members.length; i++) {
(function(idx){
User.indOne({ slack_id: slack_data.members[idx].id }, (err, user) => {
if (typeof user === 'undefined') {
newUsers.push({
name: slack_data.members[idx].real_name,
slack_id: slack_data.members[idx].id,
slack_image: slack_data.members[idx].profile.image_192,
slack_image_48: slack_data.members[idx].profile.image_48,
slack_image_512: slack_data.members[idx].profile.image_512
});
};
});
}(i));
}
User.insertMany(newUsers, (err, newSlackUsers) => {
console.log('New slack users created ', newSlackUsers);
});
}
答案 1 :(得分:0)
您在查找
中做错了User.findOne({slack_id: slack_data.members[i].id})
.then((user) => {
if (user) {
console.log('User already exists');
} else {
//Create new User.
}
})
.catch((err) => {
//handle Error
});