Date correctly updated but test fails - QA - Issue Tracker

Yohhh, this project has been crazy dodgy: been working on it for 3-4 days already :face_with_spiral_eyes: :face_with_spiral_eyes: I will really appreciate it if anyone can pinpoint what the problem is here, as the output does match what the tests require (I strive to add explanatory comments to make my code easy to follow, so I hope to make it easy for anyone who attempts to see where the issue is. Feel free to give feedback on whether said comments are helpful or not!)

Only one test is failing now (plus the test for the functional tests which I’ve yet to write):

You can send a PUT request to /api/issues/{projectname} with an _id and one or more fields to update. On success, the updated_on field should be updated, and returned should be { result: 'successfully updated', '_id': _id }.

Console message:

[Error: expected 1711202836287 to be above 1711202836287]

I’m assuming it’ s comparing the updated_on field with the created_on field. The thing is, the updated_on IS updated and it’s always above the value for created_on, both in manual tests as well as in automated tests:

{
    "_id": "65fee215808ad39bc0a1fe34",
    "issue_title": "Issue to be Updated",
    "issue_text": "New Issue Text",
    "created_by": "fCC",
    "assigned_to": "",
    "open": true,
    "status_text": "",
    "project_name": "fcc-project",
    "created_on": "2024-03-23T14:07:17.340Z", <--- //HERE
    "updated_on": "2024-03-23T14:07:17.457Z", <--- //HERE
    "__v": 0
  }

The test/error string is quite lengthy, but I believe the relevant snippet would be:

    const getUpdatedId = await $.get(url + '?_id=' + itemToUpdate._id);
    assert.isArray(getUpdatedId);
    assert.isObject(getUpdatedId[0]);
    assert.isAbove(
      Date.parse(getUpdatedId[0].updated_on), <--- HERE
      Date.parse(getUpdatedId[0].created_on)  <--- HERE
    );

Seeing as the .isAbove() test is the one being triggered, I’m assuming that .isArray and .isObject are passing and that the object is retrieved correctly.

Also, if 1711202836287 is a unixtimestamp, then it would correspond to the date 2024-11-27T00:30:03.613Z which is eight months from now (Nov. 27), so I’ve no idea why the tests would read that value, let alone expect it to be higher.

My code:

It is entirely possible that I’m dragging some mistake from previous methods, routing, database setup, etc., (or that Im wrong about the UNIX timestamp actually being a UNIX timestamp) but for now, keep in mind that all the other tests pass . The snippet for my .put() method is:

.put(function (req, res){
      let project = req.params.project;  // DIDN'T USE IT IN THIS CASE, AS THE DOCUMENT CAN BE FOUND USING ITS _ID
      let _id = req.body._id;
      // IF _ID WAS NOT SENT:
      if(!_id){
        res.send({error: 'missing _id'});
        return
      };
      // CREATE OBJECT WITH VALUES FROM INPUT FIELDS TO COMPARE
      let obj = {
       "issue_title": req.body.issue_title,
       "issue_text": req.body.issue_text,
       "created_by" : req.body.created_by,
       "assigned_to": req.body.assigned_to,
       "open" :req.body.open, //|| "", 
       "status_text": req.body.status_text
      }

      // IF ALL INPUT FIELDS ARE EMPTY:
      if(Object.values(obj).every(field=>!field)){
          // SEND ERROR
          res.send({error: 'no update field(s) sent', '_id': _id});
          return
      }

      // IF THERE'S SOMETHING TO CHANGE
      Issue.findById({"_id": _id})
      .then(data => {
        // LOOP THROUGH ALL THE SUBMITTED FIELDS
        for(let key in obj) {
          // IF SUBMITTED FIELD IS DIFFERENT FROM ORIGINAL FIELD AND IT'S NOT AN EMPTY STRING
          if(data[key] != obj[key] && obj[key] ){
            // UPDATE ORIGINAL FIELD TO NEW FIELD
            data[key] = obj[key]
          }
        }
        // SET UPDATE DATE
        data.updated_on = new Date();
        // SAVE UPDATED DATA IN MONGOOSE
        data.save()
        // IF SUCCESSFUL
        .then(updatedData=>{
          res.send({result: 'successfully updated', '_id': _id});
        })
        // IF UNSUCCESSFUL
        .catch(err=>{
          res.send({error: 'could not update', '_id': _id})
        })
      })
      // IF MONGO FAILED TO FIND OBJECT BY ID
      .catch(err=>{
        res.send({error: 'could not update', '_id': _id})
      })
    }) 

FULL api.js FILE ON GITHUB REPOSITORY:

https://github.com/RodrigoHLC/fcc-issue-tracker/tree/main/routes

Mongo Schema Setup:

const issueSchema = new mongoose.Schema({
  "issue_title": {
    type: String,
    required: true,
    // unique: true
  },
  "issue_text": {
    type: String,
    required: true
  },
  "created_on": {
    type: Date,
    default: Date.now
  },
  "updated_on": {
    type: Date,
    default: Date.now
  },
  "created_by": {
    type: String,
    required: true
  },
  "assigned_to": {
    type: String,
    default: ""
  }
  ,
  "open": {
    type: Boolean,
    default: true
  },
  "status_text": {
    type: String,
    default: ""
  },
  "project_name": {
    type: String
  }
})

My dependencies:

"dependencies": {
		"body-parser": "^1.19.0",
		"chai": "^4.2.0",
		"chai-http": "^4.3.0",
		"cors": "^2.8.5",
		"dotenv": "^8.2.0",
		"express": "^4.17.1",
		"mocha": "^8.1.3",
		"moment": "^2.30.1",
		"mongodb": "^6.5.0",
		"mongoose": "^8.2.2"
	}

FAQ

  1. I’m running the project locally
  2. I have emptied the MongoDB database before running the tests several times.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36

Challenge Information:

Quality Assurance Projects - Issue Tracker

UPDATE

Following a reply from @lasjorg in a different post

Might have something to do with the timestamps option. Which if you want an automatic created_at, and updated_at would be better to use it anyway.
https://mongoosejs.com/docs/guide.html#timestamps

I have now added the timestamps option to my schema, set the key names to the ones used in the project
{...schema keys...}, { timestamps: { createdAt: 'created_on', updatedAt: 'updated_on' }}
(I did comment out the fields for created_on and updated_on in the schema keys),
and commented out the data.updated_on = new Date() line that manually updated the date.

All other tests continue to pass and I seem to have done it correctly, because documents are being properly updated and the updated_on key continues to be higher than the created_on key.

{
    "_id": "65fef24759c2bd05220820be",
    "issue_title": "Issue to be Updated",
    "issue_text": "New Issue Text",
    "created_by": "fCC",
    "assigned_to": "",
    "open": true,
    "status_text": "--- NUEVO STATUS ---",
    "project_name": "fcc-project",
    "created_on": "2024-03-23T15:16:23.965Z", <---
    "updated_on": "2024-03-23T15:19:33.958Z", <---
    "__v": 0
  }

Alas, the test continues to fail.

Solved it thanks to two comments from a different post.

and

So yeah, my GET wasn’t using _id to fetch issues, as it didn’t need to, but apparently the tests do and needed my GET to use _id (that’s what I gather from this, at least)

Also learned an extremely hard lesson about the importance of creating objects BEFORE running Model.methods() and referencing said objects as arguments, instead of putting the entire object inside the parenthesis.