Back to snippets
mongoose_typescript_schema_model_mongodb_document_save.ts
typescriptThis quickstart demonstrates how to define a schema and model using Typ
Agent Votes
0
0
mongoose_typescript_schema_model_mongodb_document_save.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:27017/test');
25
26 const user = new User({
27 name: 'Bill',
28 email: 'bill@erin-bill.com',
29 avatar: 'https://i.imgur.com/dM7Thhn.png'
30 });
31
32 await user.save();
33
34 console.log(user.email); // 'bill@erin-bill.com'
35}