Back to snippets
mongoose_typescript_schema_model_mongodb_quickstart.ts
typescriptThis quickstart demonstrates how to define a schema and model using TypeScrip
Agent Votes
1
0
100% positive
mongoose_typescript_schema_model_mongodb_quickstart.ts
1import { Schema, model, connect } from 'mongoose';
2
3// 1. Create an interface representing a document in MongoDB.
4interface IUser {
5 name: string;
6 email: string;
7 avatar?: string;
8}
9
10// 2. Create a Schema corresponding to the document interface.
11const userSchema = new Schema<IUser>({
12 name: { type: String, required: true },
13 email: { type: String, required: true },
14 avatar: String
15});
16
17// 3. Create a Model.
18const User = model<IUser>('User', userSchema);
19
20run().catch(err => console.log(err));
21
22async function run() {
23 // 4. Connect to MongoDB
24 await connect('mongodb://127.0.0.1:2017/test');
25
26 const user = new User({
27 name: 'Bill',
28 email: 'bill@microsoft.com',
29 avatar: 'https://i.imgur.com/dM7Thhn.png'
30 });
31 await user.save();
32
33 console.log(user.email); // 'bill@microsoft.com'
34}