Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active August 24, 2023 17:24
Show Gist options
  • Save jim-clark/57b646abbb6c0ce09f9fa948eab6febc to your computer and use it in GitHub Desktop.
Save jim-clark/57b646abbb6c0ce09f9fa948eab6febc to your computer and use it in GitHub Desktop.

Perform CRUD Using Mongoose Models in a Node REPL

  1. Start by opening a terminal session and make sure that you are in the project's root folder.

  2. Start a Node REPL:

    $ node
    > 
  3. Connect to the MongoDB database:

    // If the db connection string is in a .env file, we need to process it just like in server.js
    > require('dotenv').config()
    // Connect to the database
    > require('./config/database')
    {}
    > Connected to MongoDB at localhost:27017
    // Press enter to return to the prompt
  4. Load the Models, for example, Movie:

    > const Movie = require('./models/movie')
  5. Curious what the Movie Model looks like?

    > Movie
    // a big object...

    Important: If you make any changes to a Model, you'll have exit Node and start again.

  6. Log all movie docs:

    > Movie.find({}, (e, movies) => {
    ... console.log(movies)
    ... })

    The find method returns a Query object that is first logged, followed by the movie docs. Press enter to return to the prompt.

  7. Anything that can be done with a Model in an Express app, can be done in the REPL including CRUD operations, manipulate individual documents, etc.

  8. Here's a way to delete all documents from a collection:

    > Movie.deleteMany({}, (err, result) => console.log(result))
    ...
    > { n: 3, ok: 1, deletedCount: 3 }

    The empty query object provided as the first argument matches all documents, so all documents were removed.

  9. And here's a way to update all documents in a collection:

    // reset all cast arrays to be empty
    > Movie.updateMany({}, {cast: []}, (err, result) => console.log(result))
    ...
    > { n: 3, nModified: 3, ok: 1 }

    The second object has the properties with their new values that you want to update.

  10. Press control + C twice to exit the REPL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment