Creating the schemas

So far, we've created the models based on the TypeScript interface and we are using them to persist the information in memory. With Mongoose, we have to introduce the schemas concept, which basically does the mapping between the code base and the MongoDB document.

Due to our two models, user and order, we must create two new schemas, also called user and order, under the src/schemas folder. The src/schemas/user.ts content is as follows: 

import { Document, Model, model, Schema } from 'mongoose'
import { default as User } from '../models/user'

export interface UserModel extends User, Document {}

export const UserSchema: Schema = new Schema({
firstName: String,
lastName: String,
email: String,
password: String,
phone: String,
userStatus: Number,
username: String,
})

export const UserModel: Model<UserModel> = model<UserModel>('User', UserSchema)

Note that we are now extending the user model and document, which is a MongoDB document mapped by Mongoose, and defining a new mongo schema called UserModel.

By definition, all resources using Mongoose have a property called _id, which is added to all MongoDB documents by default, and have a default type of ObjectId.

The same idea applies to the src/schemas/order.ts file:

import { Document, Model, model, Schema } from 'mongoose'
import { default as Order } from '../models/order'
import { OrderStatus } from '../models/orderStatus'

export interface OrderModel extends Order, Document {}

export const OrderSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'User' },
quantity: Number,
shipDate: Date,
status: { type: String, enum: ['PLACED', 'APPROVED', 'DELIVERED'] },
complete: Boolean,
})

export const OrderModel: Model<OrderModel> = model<OrderModel>(
'Order',
OrderSchema
)

Note that OrderSchema is referring to the userId directly to the schema user:

...
userId: { type: Schema.Types.ObjectId, ref: 'User' },
...

So, it is now required that the user exists before we create a new order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.193.172