gpt4 book ai didi

node.js - MongoDB 和 API 集成 - 如果不存在则创建新用户

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:32 24 4
gpt4 key购买 nike

我正在尝试在 MongoDB 上维护一个用户表,其中包含我们可以从 Slack API 访问的 Slack channel 中的摘录。目前,我试图在每次加载服务器时检查该 channel 是否有新成员,如果有,则创建一个新用户。

下面的脚本当前告诉我所有用户都已存在,但我的用户表目前只有 1 个条目,它应该创建另外 6 个用户。slack_data是调用slack 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 条用户记录。

slack 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
},

您能帮我找出问题所在并建议我如何执行所需的用户创建吗?

根据下面选定的答案进行编辑

使用 Await 选项,我的代码现在如下所示:

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;

最佳答案

find() 方法是异步的,由于它们的异步性质,无法确定这些函数何时完成,或者将它们放入 for 循环中时它们将按什么顺序完成。

有几种方法可以解决这个问题。您可以使用在 findOne()find() 方法上调用 exec() 方法时返回的默认 Promise。

您还可以拥抱 async/await,其中 async 函数可以被 wait/promise 阻止,因此可以阻止数组迭代,直到等待响应。

另一种选择是使用立即调用的匿名函数,它确保使用索引变量的正确值调用异步函数。

让我们通过示例来探讨每个选项。

使用 Promise

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

关于node.js - MongoDB 和 API 集成 - 如果不存在则创建新用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52466039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com