fix: refactor migration and sort old convos correctly

This commit is contained in:
Danny Avila 2023-03-14 14:51:26 -04:00
parent 71fc86b9a6
commit 9a17e94f8f

View file

@ -97,7 +97,7 @@ module.exports = {
// const limit = pageNumber * pageSize; // const limit = pageNumber * pageSize;
const conversations = await Conversation.find({}) const conversations = await Conversation.find({})
.sort({ createdAt: -1 }) .sort({ createdAt: -1, created: -1 })
.skip(skip) .skip(skip)
// .limit(limit) // .limit(limit)
.limit(pageSize) .limit(pageSize)
@ -129,7 +129,7 @@ module.exports = {
const conversations = await Conversation.find({ model: null }).exec(); const conversations = await Conversation.find({ model: null }).exec();
if (!conversations || conversations.length === 0) if (!conversations || conversations.length === 0)
return { message: 'No conversations to migrate' }; return { message: '[Migrate] No conversations to migrate' };
for (let convo of conversations) { for (let convo of conversations) {
const messages = await getMessages({ const messages = await getMessages({
@ -137,22 +137,20 @@ module.exports = {
messageId: { $exists: false } messageId: { $exists: false }
}); });
const promises = [];
let model; let model;
let oldId; let oldId;
const promises = [];
messages.forEach((message, i) => { messages.forEach((message, i) => {
const msgObj = message.toObject(); const msgObj = message.toObject();
const newId = msgObj.id; const newId = msgObj.id;
if (i === 0) { if (i === 0) {
message.parentMessageId = '00000000-0000-0000-0000-000000000000'; message.parentMessageId = '00000000-0000-0000-0000-000000000000';
oldId = newId;
} else { } else {
message.parentMessageId = oldId; message.parentMessageId = oldId;
oldId = newId;
} }
oldId = newId;
message.messageId = newId; message.messageId = newId;
message.createdAt = message.created;
if (message.sender.toLowerCase() !== 'user' && !model) { if (message.sender.toLowerCase() !== 'user' && !model) {
model = message.sender.toLowerCase(); model = message.sender.toLowerCase();
} }
@ -166,7 +164,7 @@ module.exports = {
await Conversation.findOneAndUpdate( await Conversation.findOneAndUpdate(
{ conversationId: convo.conversationId }, { conversationId: convo.conversationId },
{ model, createdAt: convo.created }, { model },
{ new: true } { new: true }
).exec(); ).exec();
} }
@ -174,11 +172,11 @@ module.exports = {
try { try {
await mongoose.connection.db.collection('messages').dropIndex('id_1'); await mongoose.connection.db.collection('messages').dropIndex('id_1');
} catch (error) { } catch (error) {
console.log("Index doesn't exist or already dropped"); console.log("[Migrate] Index doesn't exist or already dropped");
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return { message: 'Error migrating conversations' }; return { message: '[Migrate] Error migrating conversations' };
} }
} }
}; };