Learn To Code

MongoDB Practice

June 08, 2021

You can find the codesandbox here.

Let’s build an API with mongodb and express:

Here’s a table with some commonly used MongoDB commands and their corresponding functions in the Mongoose library, which is a popular Object-Document Mapping (ODM) library for Node.js that provides a more intuitive and powerful API for MongoDB:

MongoDB Command Mongoose Function
db.createCollection() N/A - Mongoose does not have a corresponding
db.collection.insertOne() MyModel.create()
db.collection.insertMany() MyModel.insertMany()
db.collection.find() MyModel.find()
db.collection.findOne() MyModel.findOne()
db.collection.updateOne() MyModel.updateOne()
db.collection.updateMany() MyModel.updateMany()
db.collection.deleteOne() MyModel.deleteOne()

Note that MyModel refers to a Mongoose model that is created by defining a schema and compiling it into a model.

Here are some examples of using Mongoose functions:

  1. Create a Mongoose model:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true }, password: String }); const User = mongoose.model('User', userSchema);`
  1. Insert data into a collection:
const user = new User({ name: 'John Doe', email: 'john@example.com', password: 'password123' }); user.save();
  1. Find data in a collection:
const users = await User.find({ name: 'John Doe' }); console.log(users);
  1. Update data in a collection:
await User.updateOne({ name: 'John Doe' }, { password: 'newpassword123' });
  1. Delete data from a collection:
await User.deleteOne({ name: 'John Doe' });