aboutsummaryrefslogtreecommitdiff
path: root/docs/guides/ecosystem/mongoose.md
blob: a36bcd134c4ec292d5cdde20b0fbc891ae0316a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
---
name: Read and write data to MongoDB using Mongoose and Bun
---

MongoDB and Mongoose work out of the box with Bun. This guide assumes you've already installed MongoDB and are running it as background process/service on your development machine. Follow [this guide](https://www.mongodb.com/docs/manual/installation/) for details.

---

Once MongoDB is running, create a directory and initialize it with `bun init`.

```bash
mkdir mongoose-app
cd mongoose-app
bun init
```

---

Then add Mongoose as a dependency.

```bash
bun add mongoose
```

---

In `schema.ts` we'll declare and export a simple `Animal` model.

```ts#schema.ts
import * as mongoose from 'mongoose';

const animalSchema = new mongoose.Schema(
  {
    name: {type: String, required: true},
    sound: {type: String, required: true},
  }
);

export type Animal = mongoose.InferSchemaType<typeof animalSchema>;
export const Animal = mongoose.model('Kitten', animalSchema);
```

---

Now from `index.ts` we can import `Animal`, connect to MongoDB, and add some data to our database.

```ts#index.ts
import * as mongoose from 'mongoose';
import {Animal} from './schema';

// connect to database
await mongoose.connect('mongodb://127.0.0.1:27017/mongoose-app');

// create new Animal
const cow = new Animal({
  name: 'Cow',
  sound: 'Moo',
});
await cow.save(); // saves to the database

// read all Animals
const animals = await Animal.find();
animals[0].speak(); // logs "Moo!"

// disconnect
await mongoose.disconnect();
```

---

Lets run this with `bun run`.

```bash
$ bun run index.ts
Moo!
```

---

This is a simple introduction to using Mongoose with TypeScript and Bun. As you build your application, refer to the official [MongoDB](https://docs.mongodb.com/) and [Mongoose](https://mongoosejs.com/docs/) sites for complete documentation.