trying to add everything but models are messy with mongoose...just nonsense from higher perspective

This commit is contained in:
talksik
2022-04-01 12:28:09 -04:00
parent ce0fb7a885
commit 5f5d977012
12 changed files with 194 additions and 128 deletions
+31 -19
View File
@@ -1,30 +1,42 @@
// External Dependencies
import * as mongoDB from "mongodb";
import { loadConfig } from "../config";
import { IUser, UserStatus } from "@nirvana/core/models/user.model";
// Global Variables
export const collections: {
users?: mongoDB.Collection;
} = {};
import { ObjectId } from "mongodb";
import { loadConfig } from "../config";
import mongoose from "mongoose";
connectToDatabase().catch((err) => console.log(err));
// Initialize Connection
export async function connectToDatabase() {
const config = loadConfig();
const client: mongoDB.MongoClient = new mongoDB.MongoClient(
config.MONGO_CONNECTION_STRING
);
await mongoose.connect(config.MONGO_CONNECTION_STRING);
await client.connect();
const db: mongoDB.Db = client.db(process.env.DB_NAME);
const usersCollection: mongoDB.Collection = db.collection("users");
collections.users = usersCollection;
console.log(
`Successfully connected to database: ${db.databaseName} and collections`
);
console.log(`Successfully connected to mongoose/mongodb`);
}
const userSchema = new mongoose.Schema<IUser>(
{
name: { type: String, required: true },
email: { type: String, required: true },
googleId: { type: String, required: true }, // our Google id that every google user has unique that we are going to use for now
verifiedEmail: Boolean,
givenName: { type: String, required: true },
familyName: { type: String, required: true },
picture: String,
locale: String,
// additional properties specific to our users collection
createdDate: Date,
status: String,
lastUpdatedDate: Date,
_id: ObjectId,
},
{ collection: "users" }
);
export const UserModel = mongoose.model<IUser>("User", userSchema);
+41 -55
View File
@@ -1,70 +1,56 @@
import { GoogleUserInfo, User } from "@nirvana/core/models";
import GoogleUserInfo from "../../core/models/googleUserInfo.model";
import { ObjectId } from "mongodb";
import { User } from "@nirvana/core/models/user.model";
import { UserModel } from "./database.service";
import { UserStatus } from "../../core/models/user.model";
import axios from "axios";
import { collections } from "./database.service";
export class UserService {
static async getUserByGoogleId(userId: string) {
const query = { googleId: userId };
const res = await collections.users?.findOne(query);
// exists
if (res?._id) {
return res as User;
}
return null;
}
static async getUserByEmail(email: string) {
const query = { email };
const res = await collections.users?.findOne(query);
const res = await UserModel.findOne({ email });
// exists
if (res?._id) {
return res as User;
if (!res?.$isEmpty) {
return res;
}
return null;
}
static async getUsersLikeEmailAndName(searchQuery: string) {
// based on index defined in Mongo atlas
const query = {
$search: {
index: "default",
text: {
query: searchQuery,
path: {
wildcard: "*",
},
},
},
};
// static async getUsersLikeEmailAndName(searchQuery: string) {
// // based on index defined in Mongo atlas
// const query = {
// $search: {
// index: "default",
// text: {
// query: searchQuery,
// path: {
// wildcard: "*",
// },
// },
// },
// };
// const res = await collections.users?.find(query).toArray();
// // const res = await collections.users?.find(query).toArray();
const res = await collections.users?.aggregate([query]).toArray();
// const res = await collections.users?.aggregate([query]).toArray();
// exists
if (res?.length) {
return res as User[];
}
// // exists
// if (res?.length) {
// return res as User[];
// }
return null;
}
// return null;
// }
static async createUserIfNotExists(newUser: User) {
const exists = (
await collections.users?.findOne({ googleId: newUser.googleId })
)?._id;
const getUser = await this.getUserByEmail(newUser.email);
if (!exists) {
return await collections.users?.insertOne(newUser);
if (!getUser) {
const newUser = new UserModel(User);
newUser.isNew = true;
return newUser.save();
}
// user with email exists already, don't create
@@ -81,14 +67,14 @@ export class UserService {
).data;
}
static async updateUserStatus(userGoogleId: string, newStatus: UserStatus) {
const query = { googleId: userGoogleId };
const updateDoc = {
$set: { status: newStatus, lastUpdatedDate: new Date() },
};
// static async updateUserStatus(userId: string, newStatus: UserStatus) {
// const query = { googleId: userGoogleId };
// const updateDoc = {
// $set: { status: newStatus, lastUpdatedDate: new Date() },
// };
const resultUpdate = await collections.users?.updateOne(query, updateDoc);
// const resultUpdate = UserModel.findByIdAndUpdate
return resultUpdate;
}
// return resultUpdate;
// }
}