# Node Course: MongoDB - Excersise 3 (Complete Pain To Work With)

**URL:** <https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026>\
**Category:** Node\
**Created:** [February 26, 2021, 2:52am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026 "2021-02-26T02:52:55Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [February 26, 2021, 2:52am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/1 "2021-02-26T02:52:55Z")

</div>

Man, this is the most annoying thing yet with this course in terms of node executing the js file. Mosh instructs you and you quadruple check your code even referencing the solution. When you try and run it using node index.js nothing returns even if your code looks exactly like mosh’s or doesn’t look like it has grammar mistakes or anything wrong with it.

I sit there for 30+ minutes comparing the solution file with my file line by line and everything looks correct yet it return this \> [] \< doesn’t return the object. This is a pain in the %^% to work with, your code may show no coding errors or anything yet not return anything.

I even went as far as to look at mongoose documentation quick start and everything. I may have to learn another database framework/lib cause this one is just so error prone without a clear indication whats wrong.

```
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises', {useNewUrlParser: true, useUnifiedTopology: true});

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number
});

const Course = mongoose.model('Course', courseSchema);

async function getAllCourses(){
  return await Course.find({isPublished: true})
  .or([{price: {$gte: 15 }}, {name: /.*by.*/i }])
  .sort({price: -1})
  .select({name: 1, author: 1, price: 1});
}

async function run(){
  const courses = await getAllCourses();
  console.log(courses);
}

// run();
// Everything above worked once i added the lines below
// it when running index.js nothing returns. 

async function getCourses(){
  const pageNumber = 2;
  const pageSize = 10;
  const courses = await Course
    .find({author: 'Mosh', isPublished: true})
    .skip((pageNumber - 1) * pageSize)
    .limit(pageSize)
    .sort({name: 1})
    .select({name: 1, tags: 1});
  console.log(courses);
}

async function updateCourse(id){

  // First Approach
  const course = await Course.findById(id);
  if (!course) return;

  course.isPublished = true;
  course.author = 'Another Author';

  const result = await course.save();
  console.log(result);
}

// this isn't working like it does when mosh calls index.js but
// it nothing looks wrong here according to the video

updateCourse('5a68fdd7bee8ea64649c2777');
```

---

<div class="post-metadata">

**Author:** ![Vikeman](https://avatars.discourse-cdn.com/v4/letter/v/4da419/32.png) [@Vikeman](https://forum.codewithmosh.com/u/Vikeman)\
**Post date:** [February 26, 2021, 7:36am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/2 "2021-02-26T07:36:33Z")

</div>

This course was made a couple years ago, so many of the npm packages he uses are several major releases ago. I had to spend a lot of time with the documentation to learn the modern method for doing the tasks he is teaching.

I finished the course a couple weeks ago (and really learned a lot) so the specific differences escape me now, but you have two choices.

- Install the same versions of the node packages that Mosh does. Pro: you can use his code and it should work. Con: You are learning outdated versions of the software. They made breaking changes (major revision) for a reason.

- Use the current versions of the packages and spend some “quality time” with the documentation. Pro: You will be up to date on the latest way to use the various packages. Con: It will take you longer to complete the class.

I opted for option 2, but I tend to be a glutton for punishment. However, scouring through the documentation for mongoose, jest and some of the others really helped cement it into my head. For the most part, the documentation is pretty good with useful examples. Sometimes there is even a migration section that shows exactly what the breaking changes were between Mosh’s version and the modern one - helps you to see if he is stepping into that changed territory or if it should be ok.

When you get to the sections on integration testing, check out a npm package called mongodb-memory-server. It will save you a ton of headaches because it runs a fresh version of the database in memory for each test and saves you a lot of errors and headaches.

Check out [How to Test Your Express API with SuperTest – Rahman Fadhil](https://rahmanfadhil.com/test-express-with-supertest/) for some good advice on how to configure your express server to save another huge pile of headaches.

Good luck!

---

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [February 26, 2021, 8:16am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/3 "2021-02-26T08:16:27Z")

</div>

Thanks for the advice, will look into that blog post once i’m done with this section. Now, if the integration testing section brings up that npm package will follow along but, don’t want to stray off the instructed path. I bought this course to learn the basics of each section and it does kinda suck that sections are outdated and maybe mosh will see this and decided to update that section (CRUD Operations Using Mongoose).

---

<div class="post-metadata">

**Author:** ![Samaty](https://avatars.discourse-cdn.com/v4/letter/s/3bc359/32.png) [@Samaty](https://forum.codewithmosh.com/u/Samaty)\
**Post date:** [March 2, 2021, 4:39am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/4 "2021-03-02T04:39:04Z")

</div>

Hi, what Vikeman said is perfectly correct but apart from the Joi package the syntaxe Mosh uses is still working perfectly fine with the last releases even if you get the classic warning message about the deprecated syntaxe.

I think your code is perfectly fine and maybe your update function doesn’t find the document id passed as argument. I would have a quick look at your collection with the GUI mongoDB Compass and see if the collection is in good shape or if anything is updated.

Make sure that the collection 'mongo-exercises does exist in your database and the Id is correct.

Good work.

---

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [March 2, 2021, 9:02am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/5 "2021-03-02T09:02:52Z")

</div>

Code is still not working, i moved onto the 18- Updating a Document- Update First video and since the update method is deprecated tried all the ones in the documentation to try and update my course object. I tried updateOne, updateMany and pretty much all the other ones. Googled xxx don’t work and looked at other people using these methods and still i’m returning. `{ n: 0, nModified: 0, ok: 1 }` I have check my code 100 times and after 1+ hour i just give up and do other things and come back to it later.

```auto
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/mongo-exercises", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .catch((err) => console.error("Error:", err));

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number,
});

const Course = mongoose.model("Course", courseSchema);

async function updateCourse(id) {
  const result = await Course.updateMany(
    { _id: id },
    {
      $set: {
        author: "Jordan"
      }
    },
    (err, doc) => {
      if (err) console.log(err);
      console.log(doc);
    }
  );
}

updateCourse("5a68fdc3615eda645bc6bdec").catch((err) => {
  console.log("Error: ", err);
});

```

No matter what \_id i put in it doesn’t get updated doesn’t mater the method I use tried most of the ones that make sense with updating a object like; findByIdAndUpdate() - findOneAndUpdate - updateMany - updateOne i’ve tried all them and the same results `{ n: 0, nModified: 0, ok: 1 }` and I go into mongodb client app and refresh and nothing changes.

---

<div class="post-metadata">

**Author:** ![jcdev](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jcdev/32/215_2.png) [@jcdev](https://forum.codewithmosh.com/u/jcdev)\
**Post date:** [March 2, 2021, 10:57am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/6 "2021-03-02T10:57:40Z")

</div>

Hi

In the schéma add \_id: String

Should work 😉

---

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [March 2, 2021, 11:30am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/7 "2021-03-02T11:30:16Z")

</div>

That seemed to fix it…ugh 2+ hours over that FML. Wish this course was updated cause he never put that \_id into his schema and it ran fine for him. Thanks for the help jcdev now i’m able to continue.

---

<div class="post-metadata">

**Author:** ![Samaty](https://avatars.discourse-cdn.com/v4/letter/s/3bc359/32.png) [@Samaty](https://forum.codewithmosh.com/u/Samaty)\
**Post date:** [March 2, 2021, 1:38pm UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/8 "2021-03-02T13:38:29Z")

</div>

Actually it worked for me without adding the \_id property to the schema. Wonder why!

---

<div class="post-metadata">

**Author:** ![jcdev](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jcdev/32/215_2.png) [@jcdev](https://forum.codewithmosh.com/u/jcdev)\
**Post date:** [March 2, 2021, 5:23pm UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/9 "2021-03-02T17:23:56Z")

</div>

\_id is normaly objectId() in mongo. As we feed the db we didn’t insert the \_id filed as an objectId() but just as String.  
Better way would be to insert \_id as objectID() not String.

---

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [March 3, 2021, 3:19am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/10 "2021-03-03T03:19:10Z")

</div>

I am onto the validation section and the validation isn’t working aka set the name property to be required when creating a new object and commented the name section out but when i run node index.js it still adds the object to the database? man i’m having non stop problems with this course not working…

When running index.js its suppose to give me an error saying name is required but it doesn’t for another  
unknown reason. If the course wasn’t outdated following it and learning wouldn’t be such a pain and slow process. At this point might buy a node course on udemy and forget about this one or any other course from mosh for that matter.

Also i’m not sure how to do this that your suggesting `_id as objectID() not String`

I tried removing \_id from the schema and createCourse function and then ran index.js with name commented out and it said ID is required so I added the ID to the schema and createCourse function and name is still commented out and ran index.js and it still saved to the database its ignoring the name validation for some reason. I can’t seem to figure it out.

```auto
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/mongo-exercises", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .catch((err) => console.error("Error:", err));

const courseSchema = new mongoose.Schema({
  _id: String,
  name: { type: String, require: true },
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number,
});

const Course = mongoose.model("Course", courseSchema);

async function createCourse() {
  const course = new Course({
    _id: mongoose.Types.ObjectId(),
    // name: "Angular Course",
    author: "Jordan",
    tags: ["angular", "frontend"],
    isPublished: true,
    price: 15,
  });

  try {
    const result = await course.save();
    console.log(result);
  } catch (err) {
    console.log(err.message);
  }
}

createCourse();

```

---

<div class="post-metadata">

**Author:** ![jcdev](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jcdev/32/215_2.png) [@jcdev](https://forum.codewithmosh.com/u/jcdev)\
**Post date:** [March 3, 2021, 9:00am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/11 "2021-03-03T09:00:41Z")

</div>

Hi jord56,

To do it, don’t mention \_id in your code schema and new Course as Mongoose will take care of it by itself.  
When you add data manualy in the db you should set \_id=“objectId(4dsf84sgf84g5g48f4hsg)” and not just \_id=“4dsf84sgf84g5g48f4hsg”.  
As you can see in Kompass, the type of \_id is actually String. with objectId(4dsf84sgf84g5g48f4hsg) it will be a type of objectId, which can be manage by mongoose as default.  
Hope I’m clear enought 😉  
jc

---

<div class="post-metadata">

**Author:** ![jord56](https://avatars.discourse-cdn.com/v4/letter/j/a88e57/32.png) [@jord56](https://forum.codewithmosh.com/u/jord56)\
**Post date:** [March 3, 2021, 8:49pm UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/12 "2021-03-03T20:49:55Z")

</div>

Even if i remove both ID’s from schema and createCourse function it still adds the new course to the database even though name is set to required? it should give me an error saying name is required but it doesn’t its like the validation isn’t working.

```auto
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/mongo-exercises", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .catch((err) => console.error("Error:", err));

const courseSchema = new mongoose.Schema({
  name: { type: String, require: true },
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number,
});

const Course = mongoose.model("Course", courseSchema);

async function createCourse() {
  const course = new Course({
    // name: "Angular Course",
    author: "Jordan",
    tags: ["angular", "frontend"],
    isPublished: true,
    price: 15,
  });

  try {
    const result = await course.save();
    console.log(result);
  } catch (err) {
    console.log(err.message);
  }
}

createCourse();

```

Update: found the reason why…look at the spelling of required? missing a d.

---

<div class="post-metadata">

**Author:** ![jcdev](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jcdev/32/215_2.png) [@jcdev](https://forum.codewithmosh.com/u/jcdev)\
**Post date:** [March 4, 2021, 10:50am UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/13 "2021-03-04T10:50:08Z")

</div>

😅

Great, I didn’t noticed the missing “d”

---

<div class="post-metadata">

**Author:** ![Osky](https://avatars.discourse-cdn.com/v4/letter/o/d2c977/32.png) [@Osky](https://forum.codewithmosh.com/u/Osky)\
**Post date:** [June 13, 2021, 11:45pm UTC](https://forum.codewithmosh.com/t/node-course-mongodb-excersise-3-complete-pain-to-work-with/3026/14 "2021-06-13T23:45:47Z")

</div>

For a paid course, we shouldn’t be having to work with outdated tools.

Ask for your money back if you can
