From 426b42266ea804e7eab20d7ed7eadbb14c2cfc11 Mon Sep 17 00:00:00 2001 From: tactonbishop Date: Thu, 11 Aug 2022 13:00:04 +0100 Subject: [PATCH] Last Sync: 2022-08-11 13:00:04 --- .../Querying_a_collection_with_Mongoose.md | 64 +++++++++++++++++++ Databases/MongoDB/Querying_a_database.md | 0 2 files changed, 64 insertions(+) create mode 100644 Databases/MongoDB/Querying_a_collection_with_Mongoose.md delete mode 100644 Databases/MongoDB/Querying_a_database.md diff --git a/Databases/MongoDB/Querying_a_collection_with_Mongoose.md b/Databases/MongoDB/Querying_a_collection_with_Mongoose.md new file mode 100644 index 0000000..3775d6f --- /dev/null +++ b/Databases/MongoDB/Querying_a_collection_with_Mongoose.md @@ -0,0 +1,64 @@ +--- +tags: +- Databases +- mongo_db +- node-js +- mongoose +--- + +# Query a Mongo collection with Mongoose + +We now have the following entries in our `courses` collection: + +```js +{ + name: 'Python Course', + author: 'Terry Ogleton', + tags: [ 'python', 'backend' ], + isPublished: true, + _id: new ObjectId("62f4e2527ac4aa2c30d41d23"), + date: 2022-08-11T11:04:50.750Z, + __v: 0 +} +{ + name: 'Javascript Course', + author: 'Tosh Gnomay', + tags: [ 'js', 'frontend' ], + isPublished: true, + _id: new ObjectId("62f4e2527ac4aa2c30d41d24"), + date: 2022-08-11T11:04:50.750Z, + __v: 0 +} + +``` + +Now we will query the collection. This capability is provided via the Mongoose schema class we used to create the `Course` [model](/Databases/MongoDB/Create_collections_and_documents_with_Mongoose.md#models). We have the following methods available to use from the schema: + +* `find` +* `findById` +* `findByIdAndRemove` +* `findByIdAndUpdate` +* `findOne` +* `findOneAndUpdate` +* `findOneAndRemove` +* ... + +The various `find` methods return a value that is promisified. + +## Return all values in a collection: `find` + +```js +async function getCourses(){ + const courses = await Course.find() + console.log(courses) +} +``` + +### Filter values returned + +```js +async function getCourses(){ + const courses = await Course.find({author: 'Tosh Gnomay', isPublished: true}) + console.log(courses) +} +``` diff --git a/Databases/MongoDB/Querying_a_database.md b/Databases/MongoDB/Querying_a_database.md deleted file mode 100644 index e69de29..0000000