Ehhh help? mongoose express excercise tracker

ehh somebody nows why my code not read the date value?
My proyect:

input: 6136ecfc8d1db32697fca13d, dsfsd, 10, 2018-12-10
output: {“username”:“Dani”,“date”:“Mon Dec 10 2018”,"_id":“6136ecfc8d1db32697fca13d”}

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const bodyParser = require('body-parser')
const mongoose = require("mongoose")
const { Schema } = mongoose;
app.use(cors())

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

mongoose.connect(process.env.DB_URI, {useNewUrlParser: true, useUnifiedTopology:true})
const UsersSchema = new Schema({
  username: String,
  count: Number,
  log: [{
    description: String,
    duration: Number,
    date: Date
  }]
})

const Users = mongoose.model("users", UsersSchema)

/*

EXCERCISE:

{
  username: "fcc_test"
  description: "test",
  duration: 60,
  date: "Mon Jan 01 1990",
  _id: "5fb5853f734231456ccb3b05"
}



LOG:
{
  username: "fcc_test",
  count: 1,
  _id: "5fb5853f734231456ccb3b05",
  log: [{
    description: "test",
    duration: 60,
    date: "Mon Jan 01 1990",
  }]
}
*/

app.post("/api/users", urlencodedParser, (req, res) => {
  const { username } = req.body

  if (username.length == 0) {
    res.json({ username: "Invalid Username" });
  } else {
    // only put username Why the var call same
    const user = new Users({
      username,
      count: 0
    })
    // save the new user below
    user.save((err, data) => {
      res.json({
        username: data.username,
        _id: data.id
      })
    })
  }
  // its fine!
})

app.post("/api/users/:_id/exercises", urlencodedParser, (req, res) => {
  const { _id } = req.params
  const { description, duration, date} = req.body
  // above its work!
  Users.findById(_id, (err, person) => {
    // above works!
    // value of the data change with a object change for keys
    person.count++;
    let time = new Date(req.body.date.toString());
    console.log(time)
    person.log.push({
      description,
      duration,
      "date": time
    })
    person.save();
    time = time.toDateString();
    res.json({
      username:person.username,
      description: person.description,
      duration: person.duration,
      "date": time,
      _id: person.id
    })
  })


})
// app.get("/api/users/:_id/logs?")


const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

It is helpful if you post your code instead of a picture of your code.

Chances are, the date formate that you are passing in req.body.date.toString() has wrong format (it will not be accepted in the new Date constructor.

I’d recommend checking what’s the value of req.body.date.toString() and then making sure the format is correct.

Cast to date failed for value “Invalid Date”

When the date is not supplied it is undefined and if you pass that into the Date constructor you get back “Invalid Date”.

new Date(undefined)
Invalid Date

You can POST to /api/users/:_id/exercises with form data description , duration , and optionally date . If no date is supplied, the current date will be used.

Screenshots are harder to debug than actual code.

input: id, sdfds, 10, 2018/12/10

app.post("/api/users/:_id/exercises", urlencodedParser, (req, res) => {
  const { _id } = req.params
  const { description, duration, date} = req.body
  // above its work!
  Users.findById(_id, (err, person) => {
    // above works!
    // value of the data change with a object change for keys
    person.count++;
    console.log(date)
    let time = new Date(req.body.date.toString());
    console.log(time)
    person.log.push({
      description,
      duration,
      "date": time
    })
    person.save();
    time = time.toDateString();
    res.json({
      username:person.username,
      description: person.description,
      duration: person.duration,
      "date": time,
      _id: person.id
    })
  })


})

Output

Your app is listening on port 3000
2018/12/10
2018-12-10T00:00:00.000Z
(node:9689) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: log.2.date: Cast to date failed for value "Invalid Date" (type string) at path "date"
    at model.Document.invalidate (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:2869:32)
    at EmbeddedDocument.Subdocument.invalidate (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/types/subdocument.js:198:12)
    at _init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:800:18)
    at init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:762:5)
    at EmbeddedDocument.Document.$__init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:731:3)
    at EmbeddedDocument.syncWrapper [as $__init] (/home/runner/Excersise-Tracker-Api/node_modules/kareem/index.js:235:23)
    at EmbeddedDocument.Document.init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:685:8)
    at EmbeddedDocument.Document.$init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:695:42)
    at DocumentArrayPath.cast (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/schema/documentarray.js:453:30)
    at _init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:798:29)
(node:9689) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9689) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Log out req.body.date. You need to handle the case where it is not supplied (i.e. it is undefined).

i change the time for

   let time = req.body.date? new Date(req.body.date.toString()):new Date();
const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const bodyParser = require('body-parser')
const mongoose = require("mongoose")
const { Schema } = mongoose;
app.use(cors())

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

mongoose.connect(process.env.DB_URI, {useNewUrlParser: true, useUnifiedTopology:true})
const UsersSchema = new Schema({
  username: String,
  count: Number,
  log: [{
    description: String,
    duration: Number,
    date: Date
  }]
})

const Users = mongoose.model("users", UsersSchema)

/*

EXCERCISE:

{
  username: "fcc_test"
  description: "test",
  duration: 60,
  date: "Mon Jan 01 1990",
  _id: "5fb5853f734231456ccb3b05"
}



LOG:
{
  username: "fcc_test",
  count: 1,
  _id: "5fb5853f734231456ccb3b05",
  log: [{
    description: "test",
    duration: 60,
    date: "Mon Jan 01 1990",
  }]
}
*/

app.post("/api/users", urlencodedParser, (req, res) => {
  const { username } = req.body

  if (username.length == 0) {
    res.json({ username: "Invalid Username" });
  } else {
    // only put username Why the var call same
    const user = new Users({
      username,
      count: 0
    })
    // save the new user below
    user.save((err, data) => {
      res.json({
        username: data.username,
        _id: data.id
      })
    })
  }
  // its fine!
})

app.post("/api/users/:_id/exercises", urlencodedParser, (req, res) => {
  const { _id } = req.params
  const { description, duration, date} = req.body
  // above its work!
  Users.findById(_id, (err, person) => {
    // above works!
    // value of the data change with a object change for keys
    person.count++;
    console.log(date)
    let time = req.body.date? new Date(req.body.date.toString()):new Date();
    console.log(time)
    person.log.push({
      description,
      duration,
      "date": time
    })
    person.save();
    time = time.toDateString();
    res.json({
      username:person.username,
      description: person.description,
      duration: person.duration,
      "date": time,
      _id: person.id
    })
  })


})
// app.get("/api/users/:_id/logs?")


const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

console.log

2018-12-10
2018-12-10T00:00:00.000Z
(node:9774) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: log.2.date: Cast to date failed for value "Invalid Date" (type string) at path "date"
    at model.Document.invalidate (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:2869:32)
    at EmbeddedDocument.Subdocument.invalidate (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/types/subdocument.js:198:12)
    at _init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:800:18)
    at init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:762:5)
    at EmbeddedDocument.Document.$__init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:731:3)
    at EmbeddedDocument.syncWrapper [as $__init] (/home/runner/Excersise-Tracker-Api/node_modules/kareem/index.js:235:23)
    at EmbeddedDocument.Document.init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:685:8)
    at EmbeddedDocument.Document.$init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:695:42)
    at DocumentArrayPath.cast (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/schema/documentarray.js:453:30)
    at _init (/home/runner/Excersise-Tracker-Api/node_modules/mongoose/lib/document.js:798:29)
(node:9774) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

Are you putting the date inside parentheses when submitting? Because that is the only way I have found I can trigger the validation error. The date should not have parentheses when submitting using the form. I know the placeholder shows it like that but it isn’t meant as the literal input.

Otherwise, I’m not seeing that validation error when I test your code using the tests or manual input (inputting the correct date format).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.