Skip to content
Chandan Kumar

Remix Run Tutorial: Mongodb connection with Mongoose

reactjs, mongodb1 min read

Refer to newer post on this at /blog/remix-mongodb-typescript-tutorial

This is a short tutorial on integrating remix.run with Mongodb using the mongoose library. Remix is a full-stack web framework. This is an intermediate level tutorial and one must know about Reactjs and MongoDB at least.

Steps

  1. Create remix project
  2. Code a Mongoose Model
  3. Initialize mongodb driver
  4. Fetch and render the data

create a Remix project

Source code for this example is at https://github.com/ch4nd4n/practice/tree/remix-run/remix-mongoose

1# Create remix project

Fill out the details, I used Typescript and remix server.

For this tutorial, we don't need routes and styles, so knock it off.

1rm -rf routes
2rm -rf styles

The next step is to create a Mongoose model to fetch todos collection from MongoDB.

Mongoose Model

/models/Todo.tsx
1import mongoose from "mongoose";
2const TodoSchema = new mongoose.Schema({
3 title: { type: String, required: true },
4});
5const model = mongoose.models.Todo || mongoose.model("Todo", TodoSchema);
6export default model;

Update root.tsx

In root.tsx we connect to Mongodb using mongoose.connect method and use remix loader to use a mongoose model. The model populates the data before the component gets rendered on the browser.

1import mongoose from "mongoose";
2import Todo from "./models/Todo";
3
4mongoose.connect(
5 "mongodb://root:[email protected]:27017/chandan_vercel_dev?authSource=admin",
6 (error) => {
7 if (!error) return console.info("Mongo connected");
8 console.error(error);
9 }
10);
11export let loader: any = async () => {
12 return await Todo.find({});
13};
14
15const TodoList = (todos: any) => {
16 return (
17 <ul>
18 {todos.map((todo: any) => (
19 <li>{todo.title}</li>
20 ))}
21 </ul>
22 );
23};

Next up

You can visit remix.run for the official documentation. I intend to explore web socket connection with Remix.

Similar article:

  1. Remix Tutorial: Firebase Authentication

Comments

Copyleft. WTH
Theme by LekoArts