Skip to content

Commit

Permalink
npm i mongoose@7.6.2
Browse files Browse the repository at this point in the history
  • Loading branch information
sspenst committed Oct 17, 2023
1 parent fd66fde commit 8c3c744
Show file tree
Hide file tree
Showing 42 changed files with 199 additions and 222 deletions.
3 changes: 2 additions & 1 deletion helpers/multiplayerHelperFunctions.ts
Expand Up @@ -2,8 +2,9 @@ import MultiplayerProfile from '../models/db/multiplayerProfile';
import { MultiplayerMatchType } from '../models/MultiplayerEnums';

export const MUTLIPLAYER_PROVISIONAL_GAME_LIMIT = 5;
export const MULTIPLAYER_INITIAL_ELO = 1000;

export function isProvisional(type: MultiplayerMatchType, profile?: MultiplayerProfile): boolean {
export function isProvisional(type: MultiplayerMatchType, profile?: MultiplayerProfile | null): boolean {
return !profile || getMatchCountFromProfile(profile, type) < MUTLIPLAYER_PROVISIONAL_GAME_LIMIT;
}

Expand Down
3 changes: 1 addition & 2 deletions helpers/notificationHelper.ts
Expand Up @@ -182,9 +182,8 @@ export async function createNewLevelNotifications(userIdWhoCreatedLevel: Types.O
targetModel: 'User',
type: GraphType.FOLLOW,
}, 'source', {
lean: true,
...options,
});
}).lean();

const ids: Types.ObjectId[] = [];
const createRecords = usersThatFollow.map(user => {
Expand Down
20 changes: 10 additions & 10 deletions helpers/refreshAchievements.ts
Expand Up @@ -5,38 +5,38 @@ import { createNewAchievement } from '@root/helpers/notificationHelper';
import { getDifficultyRollingSum } from '@root/helpers/playerRankHelper';
import Achievement from '@root/models/db/achievement';
import Level from '@root/models/db/level';
import MultiplayerMatch from '@root/models/db/multiplayerMatch';
import MultiplayerProfile from '@root/models/db/multiplayerProfile';
import Review from '@root/models/db/review';
import User from '@root/models/db/user';
import { AchievementModel, LevelModel, MultiplayerMatchModel, MultiplayerProfileModel, ReviewModel, UserModel } from '@root/models/mongoose';
import { Types } from 'mongoose';

const AchievementCategoryFetch = {
[AchievementCategory.USER]: async (userId: Types.ObjectId) => {
const user = await UserModel.findById<User>(userId, {}, { lean: true });
const user = await UserModel.findById(userId).lean<User>();

return { user: user };
},
[AchievementCategory.REVIEWER]: async (userId: Types.ObjectId) => {
const reviewsCreated = await ReviewModel.find<Review>({ userId: userId, isDeleted: { $ne: true } }, {}, { lean: true });
const reviewsCreated = await ReviewModel.find({ userId: userId, isDeleted: { $ne: true } }).lean<Review[]>();

return { reviewsCreated: reviewsCreated };
},
[AchievementCategory.MULTIPLAYER]: async (userId: Types.ObjectId) => {
const [userMatches, multiplayerProfile] = await Promise.all(
[
MultiplayerMatchModel.find({ players: userId, rated: true }, { players: 1, winners: 1, createdAt: 1, createdBy: 1 }, { lean: true }),
MultiplayerProfileModel.findOne({ userId: userId }, {}, { lean: true })
MultiplayerMatchModel.find({ players: userId, rated: true }, { players: 1, winners: 1, createdAt: 1, createdBy: 1 }).lean<MultiplayerMatch[]>(),
MultiplayerProfileModel.findOne({ userId: userId }).lean<MultiplayerProfile>(),
]
);

return { userMatches: userMatches, multiplayerProfile: multiplayerProfile };
},
[AchievementCategory.CREATOR]: async (userId: Types.ObjectId) => {
const userCreatedLevels = await LevelModel.find<Level>(
{
userId: userId, isDraft: false, isDeleted: { $ne: true },
}, { score: 1, authorNote: 1, leastMoves: 1, ts: 1, calc_reviews_score_laplace: 1, calc_playattempts_just_beaten_count: 1, calc_playattempts_unique_users: 1, calc_reviews_count: 1 },
{ lean: true });
const userCreatedLevels = await LevelModel.find(
{ userId: userId, isDraft: false, isDeleted: { $ne: true } },
{ score: 1, authorNote: 1, leastMoves: 1, ts: 1, calc_reviews_score_laplace: 1, calc_playattempts_just_beaten_count: 1, calc_playattempts_unique_users: 1, calc_reviews_count: 1 }).lean<Level[]>();

return { levelsCreated: userCreatedLevels };
},
Expand Down Expand Up @@ -64,7 +64,7 @@ export async function refreshAchievements(userId: Types.ObjectId, categories: Ac

const [neededDataArray, allAchievements] = await Promise.all([
Promise.all(fetchPromises),
AchievementModel.find<Achievement>({ userId: userId }, { type: 1, }, { lean: true }),
AchievementModel.find({ userId: userId }, { type: 1, }).lean<Achievement[]>(),
]);
// neededDataArray is an array of objects with unique keys. Let's combine into one big object
const neededData = neededDataArray.reduce((acc, cur) => ({ ...acc, ...cur }), {});
Expand Down
4 changes: 2 additions & 2 deletions lib/withAuth.ts
Expand Up @@ -70,8 +70,8 @@ export async function getUserFromToken(
}),
...ipData,
},
{ lean: true, new: true, projection: '+email +bio' },
);
{ new: true, projection: '+email +bio' },
).lean<User>();

if (user && !isLocal()) {
newrelic.addCustomAttribute && newrelic.addCustomAttribute('userName', user.name);
Expand Down
1 change: 1 addition & 0 deletions models/db/multiplayerProfile.d.ts
@@ -1,4 +1,5 @@
interface MultiplayerProfile {
_id: Types.ObjectId;
calcRushBulletCount: number;
calcRushBlitzCount: number;
calcRushRapidCount: number;
Expand Down
10 changes: 5 additions & 5 deletions models/schemas/multiplayerProfileSchema.ts
@@ -1,3 +1,4 @@
import { MULTIPLAYER_INITIAL_ELO } from '@root/helpers/multiplayerHelperFunctions';
import mongoose from 'mongoose';
import MultiplayerProfile from '../db/multiplayerProfile';

Expand Down Expand Up @@ -26,29 +27,28 @@ const MultiplayerProfileSchema = new mongoose.Schema<MultiplayerProfile>(
ratingRushBullet: {
type: Number,
required: true,
default: 1000,
default: MULTIPLAYER_INITIAL_ELO,
},
ratingRushBlitz: {
type: Number,
required: true,
default: 1000,
default: MULTIPLAYER_INITIAL_ELO,
},
ratingRushRapid: {
type: Number,
required: true,
default: 1000,
default: MULTIPLAYER_INITIAL_ELO,
},
ratingRushClassical: {
type: Number,
required: true,
default: 1000,
default: MULTIPLAYER_INITIAL_ELO,
},
ratingDeviation: {
type: Number,
required: true,
default: 400,
},

userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
Expand Down
40 changes: 14 additions & 26 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -25,7 +25,7 @@
"micro": "^10.0.1",
"module-alias": "^2.2.3",
"moment": "^2.29.4",
"mongoose": "^7.4.2",
"mongoose": "^7.6.2",
"newrelic": "^11.1.0",
"next": "^13.5.4",
"next-seo": "^6.1.0",
Expand Down
3 changes: 2 additions & 1 deletion pages/_document.tsx
@@ -1,4 +1,5 @@
/* istanbul ignore file */
import User from '@root/models/db/user';
import { Types } from 'mongoose';
import Document, { DocumentContext, DocumentInitialProps, Head, Html, Main, NextScript } from 'next/document';
import React from 'react';
Expand Down Expand Up @@ -55,7 +56,7 @@ if (process.env.OFFLINE_BUILD !== 'true') {

logger.warn('[Run ID ' + containerRunInstanceId + '] Starting... Trying to connect to DB');
dbConnect().then(async () => { // Hopefully this works... and prevents the big spike in performance on every deploy...
await UserModel.findOne({}, { _id: 1 }, { lean: true });
await UserModel.findOne({}, { _id: 1 }).lean<User>();

logger.warn('[Run ID ' + containerRunInstanceId + '] Connected to database and ran a sample query in ' + (Date.now() - benchmark_start) + 'ms');
});
Expand Down
3 changes: 2 additions & 1 deletion pages/api/avatar/[id].ts
@@ -1,3 +1,4 @@
import Image from '@root/models/db/image';
import { NextApiRequest, NextApiResponse } from 'next';
import apiWrapper, { ValidObjectIdPNG } from '../../../helpers/apiWrapper';
import dbConnect from '../../../lib/dbConnect';
Expand All @@ -24,7 +25,7 @@ export default apiWrapper({ GET: {
});
}

const image = await ImageModel.findOne({ documentId: userId }, {}, { lean: false });
const image = await ImageModel.findOne<Image>({ documentId: userId });

if (image) {
res.setHeader('Content-Type', 'image/png');
Expand Down
14 changes: 4 additions & 10 deletions pages/api/comment/[id].ts
Expand Up @@ -171,12 +171,10 @@ export default withAuth({
}
} else if (targetModel === 'Comment') {
const [parentComment, everyoneInThread] = await Promise.all([
CommentModel.findOne<Comment>({
CommentModel.findOne({
_id: target,
deletedAt: null,
}, {}, {
lean: true
}),
}).lean<Comment>(),
CommentModel.aggregate([
{
$match: {
Expand Down Expand Up @@ -261,15 +259,11 @@ async function softDeleteComment(commentId: Types.ObjectId, reqUser: User): Prom
CommentModel.findOne({
_id: comment.target,
deletedAt: null
}, {}, {
lean: true
}),
}).lean<Comment>(),
CommentModel.find({
target: comment._id,
deletedAt: null
}, {}, {
lean: true
})
}).lean<Comment[]>(),
]);

const promises = [];
Expand Down
2 changes: 1 addition & 1 deletion pages/api/edit/[id].ts
Expand Up @@ -20,7 +20,7 @@ export default withAuth({
} }, async (req: NextApiRequestWithAuth, res: NextApiResponse) => {
await dbConnect();
const { id } = req.query;
const level = await LevelModel.findOne<Level>({ _id: id, isDeleted: { $ne: true } }, {}, { lean: true });
const level = await LevelModel.findOne({ _id: id, isDeleted: { $ne: true } }).lean<Level>();

if (!level) {
return res.status(404).json({
Expand Down
3 changes: 1 addition & 2 deletions pages/api/follow/index.ts
Expand Up @@ -55,8 +55,7 @@ export default withAuth({

const updateResult = await GraphModel.updateOne(query, query, {
upsert: true,
lean: true,
});
}).lean();

if (updateResult.upsertedCount === 1) {
await createNewFollowerNotification(req.userId, id as string);
Expand Down
2 changes: 1 addition & 1 deletion pages/api/guest-convert/index.ts
Expand Up @@ -35,7 +35,7 @@ export default withAuth({
password,
} = req.body;

const user = await UserModel.findById(req.userId, '+password', { lean: false });
const user = await UserModel.findById(req.userId, '+password');
const trimmedName = name.trim();

user.email = email.trim();
Expand Down
5 changes: 2 additions & 3 deletions pages/api/internal-jobs/worker/index.ts
Expand Up @@ -265,10 +265,9 @@ export async function processQueueMessages() {
isProcessing: false,
}, {}, {
session: session,
lean: true,
limit: 10,
sort: { priority: -1, createdAt: 1 },
});
}).lean<QueueMessage[]>();

if (queueMessages.length === 0) {
found = false;
Expand All @@ -287,7 +286,7 @@ export async function processQueueMessages() {
$inc: {
processingAttempts: 1,
},
}, { session: session, lean: true });
}, { session: session }).lean();

// manually update queueMessages so we don't have to query again
queueMessages.forEach(message => {
Expand Down
6 changes: 4 additions & 2 deletions pages/api/internal-jobs/worker/sendEmailNotification.ts
@@ -1,12 +1,14 @@
import getEmailBody from '@root/helpers/getEmailBody';
import getMobileNotification from '@root/helpers/getMobileNotification';
import Notification from '@root/models/db/notification';
import User from '@root/models/db/user';
import UserConfig from '@root/models/db/userConfig';
import { EmailLogModel, UserConfigModel, UserModel } from '@root/models/mongoose';
import { Types } from 'mongoose';
import { sendMail } from '../email-digest';

export async function sendEmailNotification(notification: Notification) {
const userConfig = await UserConfigModel.findOne({ userId: notification.userId }, { emailNotificationsList: 1 }, { lean: true });
const userConfig = await UserConfigModel.findOne({ userId: notification.userId }, { emailNotificationsList: 1 }).lean<UserConfig>();
const validTypes = userConfig?.emailNotificationsList || [];

if (validTypes.includes(notification.type)) {
Expand All @@ -16,7 +18,7 @@ export async function sendEmailNotification(notification: Notification) {
}).sort({ createdAt: -1 });

const lastSentTime = lastSent ? new Date(lastSent.createdAt).getTime() : 0;
const lastLoggedInTimeQuery = await UserModel.findOne({ _id: notification.userId }, { last_visited_at: 1 }, { lean: true });
const lastLoggedInTimeQuery = await UserModel.findOne({ _id: notification.userId }, { last_visited_at: 1 }).lean<User>();
const lastLoggedInTime = lastLoggedInTimeQuery?.last_visited_at ? new Date(1000 * lastLoggedInTimeQuery.last_visited_at).getTime() : 0;

// check if it has been less than 24 hours since last email
Expand Down

0 comments on commit 8c3c744

Please sign in to comment.