Skip to content

Commit 7a979eb

Browse files
update the mongoose tutorial to use latest mongoose (#2682)
1 parent 5b1c639 commit 7a979eb

File tree

1 file changed

+73
-53
lines changed

1 file changed

+73
-53
lines changed

examples/tutorials/mongoose.md

Lines changed: 73 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -31,26 +31,51 @@ touch main.ts && mkdir model && touch model/Dinosaur.ts
3131
In `/model/Dinosaur.ts`, we'll import `npm:mongoose`, define the [schema], and
3232
export it:
3333

34-
```ts
35-
import { model, Schema } from "npm:mongoose@^6.7";
36-
37-
// Define schema.
38-
const dinosaurSchema = new Schema({
39-
name: { type: String, unique: true },
40-
description: String,
41-
createdAt: { type: Date, default: Date.now },
42-
updatedAt: { type: Date, default: Date.now },
43-
});
44-
45-
// Validations
46-
dinosaurSchema.path("name").required(true, "Dinosaur name cannot be blank.");
47-
dinosaurSchema.path("description").required(
48-
true,
49-
"Dinosaur description cannot be blank.",
34+
```ts title="model/Dinosaur.ts"
35+
import mongoose, {
36+
type HydratedDocument,
37+
type Model,
38+
model,
39+
models,
40+
Schema,
41+
} from "npm:mongoose@latest";
42+
43+
interface Dinosaur {
44+
name: string;
45+
description: string;
46+
createdAt?: Date;
47+
updatedAt?: Date;
48+
}
49+
50+
interface DinosaurMethods {
51+
updateDescription(
52+
this: HydratedDocument<Dinosaur>,
53+
description: string,
54+
): Promise<
55+
HydratedDocument<Dinosaur>
56+
>;
57+
}
58+
59+
type DinosaurModel = Model<Dinosaur, {}, DinosaurMethods>;
60+
61+
const dinosaurSchema = new Schema<Dinosaur, DinosaurModel, DinosaurMethods>(
62+
{
63+
name: { type: String, unique: true, required: true },
64+
description: { type: String, required: true },
65+
},
66+
{ timestamps: true },
5067
);
5168

52-
// Export model.
53-
export default model("Dinosaur", dinosaurSchema);
69+
dinosaurSchema.methods.updateDescription = async function (
70+
this: HydratedDocument<Dinosaur>,
71+
description: string,
72+
) {
73+
this.description = description;
74+
return await this.save();
75+
};
76+
77+
export default (models.Dinosaur as DinosaurModel) ||
78+
model<Dinosaur, DinosaurModel>("Dinosaur", dinosaurSchema);
5479
```
5580

5681
## Connecting to MongoDB
@@ -59,42 +84,41 @@ Now, in our `main.ts` file, we'll import mongoose and the `Dinosaur` schema, and
5984
connect to MongoDB:
6085

6186
```ts
62-
import mongoose from "npm:mongoose@^6.7";
87+
import mongoose from "npm:mongoose@latest";
6388
import Dinosaur from "./model/Dinosaur.ts";
6489

65-
await mongoose.connect("mongodb://localhost:27017");
90+
const MONGODB_URI = Deno.env.get("MONGODB_URI") ??
91+
"mongodb://localhost:27017/deno_mongoose_tutorial";
92+
93+
await mongoose.connect(MONGODB_URI);
6694

67-
// Check to see connection status.
6895
console.log(mongoose.connection.readyState);
6996
```
7097

7198
Because Deno supports top-level `await`, we're able to simply
7299
`await mongoose.connect()`.
73100

74-
Running this, we should expect a log of `1`:
101+
Running the code with this command:
75102

76103
```shell
77-
$ deno run --allow-read --allow-sys --allow-env --allow-net main.ts
78-
1
104+
deno run --allow-env --allow-net main.ts
79105
```
80106

81-
It worked!
107+
We expect a log of `1`.
82108

83109
## Manipulating Data
84110

85-
Let's add an instance [method](https://mongoosejs.com/docs/guide.html#methods)
86-
to our `Dinosaur` schema in `/model/Dinosaur.ts`:
87-
88-
```ts
89-
// ./model/Dinosaur.ts
90-
91-
// Methods.
92-
dinosaurSchema.methods = {
93-
// Update description.
94-
updateDescription: async function (description: string) {
95-
this.description = description;
96-
return await this.save();
97-
},
111+
Let's add a typed instance
112+
[method](https://mongoosejs.com/docs/guide.html#methods) to our `Dinosaur`
113+
schema in `/model/Dinosaur.ts`:
114+
115+
```ts title="model/Dinosaur.ts"
116+
dinosaurSchema.methods.updateDescription = async function (
117+
this: HydratedDocument<Dinosaur>,
118+
description: string,
119+
) {
120+
this.description = description;
121+
return await this.save();
98122
};
99123

100124
// ...
@@ -105,31 +129,26 @@ description.
105129

106130
Back in `main.ts`, let's start adding and manipulating data in MongoDB.
107131

108-
```ts
109-
// main.ts
110-
111-
// Create a new Dinosaur.
132+
```ts title="main.ts"
112133
const deno = new Dinosaur({
113134
name: "Deno",
114-
description: "The fastest dinosaur ever lived.",
135+
description: "The fastest dinosaur that ever lived.",
115136
});
116137

117-
// // Insert deno.
118138
await deno.save();
119139

120-
// Find Deno by name.
121-
const denoFromMongoDb = await Dinosaur.findOne({ name: "Deno" });
140+
const denoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }).exec();
141+
if (!denoFromMongoDb) throw new Error("Deno not found");
122142
console.log(
123143
`Finding Deno in MongoDB -- \n ${denoFromMongoDb.name}: ${denoFromMongoDb.description}`,
124144
);
125145

126-
// Update description for Deno and save it.
127146
await denoFromMongoDb.updateDescription(
128-
"The fastest and most secure dinosaur ever lived.",
147+
"The fastest and most secure dinosaur that ever lived.",
129148
);
130149

131-
// Check MongoDB to see Deno's updated description.
132-
const newDenoFromMongoDb = await Dinosaur.findOne({ name: "Deno" });
150+
const newDenoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }).exec();
151+
if (!newDenoFromMongoDb) throw new Error("Deno not found after update");
133152
console.log(
134153
`Finding Deno (again) -- \n ${newDenoFromMongoDb.name}: ${newDenoFromMongoDb.description}`,
135154
);
@@ -139,12 +158,13 @@ Running the code, we get:
139158

140159
```console
141160
Finding Deno in MongoDB --
142-
Deno: The fastest dinosaur ever lived.
161+
Deno: The fastest dinosaur that ever lived.
143162
Finding Deno (again) --
144-
Deno: The fastest and most secure dinosaur ever lived.
163+
Deno: The fastest and most secure dinosaur that ever lived.
145164
```
146165

147-
Boom!
166+
🦕 Now you have a fully functional Deno application using Mongoose to interact
167+
with MongoDB!
148168

149169
For more info on using Mongoose, please refer to
150170
[their documentation](https://mongoosejs.com/docs/guide.html).

0 commit comments

Comments
 (0)