mongo in typescript

To start using MongoDB with TypeScript, you need to install the mongoose package.

You can use npm, the Node Package Manager, to install mongoose and its corresponding type definitions by running the following command in your project’s root directory:

index.ts
npm install mongoose @types/mongoose
37 chars
2 lines

After installing these packages, you can start using mongoose in your TypeScript application. Here’s an example of how to create a simple mongoose schema:

index.ts
import { Document, Schema, model } from 'mongoose';

interface IUser extends Document {
  email: string;
  password: string;
}

const userSchema = new Schema({
  email: String,
  password: String
});

const User = model<IUser>('User', userSchema);

export { IUser, User };
273 chars
16 lines

In this example, we define a userSchema with two fields: email and password. We also define an IUser interface that extends Document, and a User model by calling the model() function with the IUser interface and userSchema as arguments.

You can then use the User model to perform CRUD (Create, Read, Update, Delete) operations on your MongoDB database.

index.ts
import { connect } from 'mongoose';
import { IUser, User } from './models/user';

(async function () {
  await connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true });

  // Create a user
  const user: IUser = await User.create({ email: 'test@test.com', password: 'password' });

  // Read users
  const users: IUser[] = await User.find({});
  console.log(users);

  // Update a user
  await User.updateOne({ _id: user._id }, { password: 'newpassword' });

  // Delete a user
  await User.deleteOne({ _id: user._id });
})();
538 chars
20 lines

In this example, we first connect to our MongoDB database using the connect() function from mongoose. We then create a user, read all users, update a user’s password, and delete a user using the User model we defined earlier.

I hope this helps you get started with MongoDB in TypeScript!

gistlibby LogSnag