Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active September 13, 2024 12:59
Show Gist options
  • Save lejonmanen/2531652f0b7333d23cdaf59a60d9283d to your computer and use it in GitHub Desktop.
Save lejonmanen/2531652f0b7333d23cdaf59a60d9283d to your computer and use it in GitHub Desktop.
Mongoose example with TypeScript
import { Schema, model, connect, Mongoose } from 'mongoose'
// Animal is an interface describing animal objects
import { Animal } from './animal.js';
const animalSchema = new Schema<WithId<Animal>>({
_id: ObjectId, // from WithId
species: String, // from Animal
factoid: String, // from Animal
score: Number // from Animal
})
// Always use the singular form. Mongoose will create a collection in the plural: "Animal" -> "animals"
const AnimalModel = model('Animal', animalSchema)
// This is where we connect to the database. Our models will use this collection. We only need the variable to close the connection.
// The connection string comes from a ".env" file. You can use the same connection string as MongoDB Compass, just add "/database-name" to the end.
const client: Mongoose = await connect(process.env.CONNECTION_STRING!)
// Get documents as an array
// This filter finds all animal documents that have score below 50
let animalsFound: Animal[] = await AnimalModel.find({ score: { $lt: 50 } });
// Add new document
const newAnimal: WithId<Animal> = {
_id: new ObjectId(),
species: 'Anaconda',
factoid: 'Interesting fact...',
score: 42
}
await AnimalModel.create(newAnimal)
// Delete document
// In this case, delete the first "Snake"
await AnimalModel.deleteOne({ species: 'Snake' })
// Update document
// In this case, find the turtle and change the species to tortoise
const updateFilter = { species: "Turtle" }
const update = { species: "Tortoise" }
await AnimalModel.updateOne(updateFilter, update)
// Don't forget to close the connection when done
client.connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment