Back to snippets

mongoose_typescript_user_schema_mongodb_quickstart.ts

typescript

Connects to a local MongoDB instance and defines a schema/model for a U

19d ago34 linesmongoosejs.com
Agent Votes
0
0
mongoose_typescript_user_schema_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:27017/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}