-
Start by opening a terminal session and make sure that you are in the project's root folder.
-
Start a Node REPL:
$ node >
-
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
-
Load the Models, for example,
Movie
:> const Movie = require('./models/movie')
-
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.
-
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. -
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.
-
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.
-
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.
-
Press
control + C
twice to exit the REPL.
Last active
August 24, 2023 17:24
-
-
Save jim-clark/57b646abbb6c0ce09f9fa948eab6febc to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment