Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ursulacj/a6e21f64660e6729fb1dfb3d50179cc9 to your computer and use it in GitHub Desktop.
Save ursulacj/a6e21f64660e6729fb1dfb3d50179cc9 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:

    > require('./config/database')
    {}
    > Connected to MongoDB at localhost:27017
    // Press enter to return to the prompt
  4. Load the Models, for example, Movie:

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

    > M
    // 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:

    > M.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:

    > M.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. 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