Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on 

How do I pass this variable into my method?

Here is my method:

 this.displayActivityForm = function (companyId, proposalId, type, activityId) {
            console.log(activityId);
            $.get('/companies/activities/' +activityId, function(resp) {
                      if (resp.error) {
                    CAMS.alert('Error', resp.msg, 'error');
                    return false;
                }
                  let type = resp.type;
                  let notes = resp.notes;
                  let date = resp.meta.date;
                  console.log(date);
            });

I can successfully do the "console.log(activityId) that you see on the second line, but there's something about the way I'm passing that value into my route that's coming up short.

First of all, here's the route:

router.get('/companies/activities/:activityId', async(req, res)=> {
      try {
            //console.log(req.params.activityId);
            let activityId=req.params.activityId;
            let activity = await Activity.getOne(activityId);
            res.send(activity);
    } catch (err) {
        res.send(error('An unexpected error was encountered while trying to load your proposal. Please try again.'));
    }
});

...and here's the Activity service:

 getOne(activityId) {
               //console.log(activityId);
        return new Promise((resolve, reject) => {
            let activity_Id = this._getId(activityId);
                  console.log(activity_Id);
            this.model.findOne({ _id: activity_Id }, (err, res) => {
                if (err) { console.log(err); reject(err); }
                resolve(res);
            });
        });
    }




Here's the error I'm getting (BTW: there's a lot here, but I have in bold what I believe the problem to be):

Error:  Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
    at new ObjectID (C:\wamp64\www\bSmart\node_modules\mongodb\node_modules\bson\lib\bson\objectid.js:59:11)
    at Activity._getId (C:\wamp64\www\bSmart\server\services\service.js:661:24)
    at C:\wamp64\www\bSmart\server\services\activity.js:27:36
    at new Promise (<anonymous>)
   at Activity.getOne (C:\wamp64\www\bSmart\server\services\activity.js:26:16)
    at C:\wamp64\www\bSmart\server\routes\companies.js:833:33

    at Layer.handle [as handle_request] (C:\wamp64\www\bSmart\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\wamp64\www\bSmart\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\wamp64\www\bSmart\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\wamp64\www\bSmart\node_modules\express\lib\router\layer.js:95:5)
    at C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:281:22
    at param (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:354:14)
    at param (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:365:14)
    at Function.process_params (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:410:3)
    at next (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:174:3)
    at router (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\wamp64\www\bSmart\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:317:13)
    at C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:335:12)
    at next (C:\wamp64\www\bSmart\node_modules\express\lib\router\index.js:275:10)
false
MongooseError [CastError]: Cast to ObjectId failed for value "false" at path "_id" for model "Activity"
    at new CastError (C:\wamp64\www\bSmart\node_modules\mongoose\lib\error\cast.js:29:11)
    at ObjectId.cast (C:\wamp64\www\bSmart\node_modules\mongoose\lib\schema\objectid.js:244:11)
    at ObjectId.SchemaType.applySetters (C:\wamp64\www\bSmart\node_modules\mongoose\lib\schematype.js:948:12)
    at ObjectId.SchemaType._castForQuery (C:\wamp64\www\bSmart\node_modules\mongoose\lib\schematype.js:1362:15)
    at ObjectId.SchemaType.castForQuery (C:\wamp64\www\bSmart\node_modules\mongoose\lib\schematype.js:1352:15)
    at ObjectId.SchemaType.castForQueryWrapper (C:\wamp64\www\bSmart\node_modules\mongoose\lib\schematype.js:1331:15)
    at cast (C:\wamp64\www\bSmart\node_modules\mongoose\lib\cast.js:307:32)
    at model.Query.Query.cast (C:\wamp64\www\bSmart\node_modules\mongoose\lib\query.js:4608:12)
    at model.Query.Query._castConditions (C:\wamp64\www\bSmart\node_modules\mongoose\lib\query.js:1790:10)
    at model.Query.<anonymous> (C:\wamp64\www\bSmart\node_modules\mongoose\lib\query.js:2045:8)
    at model.Query._wrappedThunk [as _findOne] (C:\wamp64\www\bSmart\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
    at C:\wamp64\www\bSmart\node_modules\mongoose\node_modules\kareem\index.js:369:33
    at processTicksAndRejections (internal/process/task_queues.js:75:11) {
  message: 'Cast to ObjectId failed for value "false" at path "_id" for model "Activity"',
  name: 'CastError',
  stringValue: '"false"',
  kind: 'ObjectId',
  value: false,
  path: '_id',
  reason: undefined,
  model: Model { Activity }
}
(node:18160) UnhandledPromiseRejectionWarning: ReferenceError: error is not defined
    at C:\wamp64\www\bSmart\server\routes\companies.js:836:13
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:18160) 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(). (rejection id: 1)
(node:18160) [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.

It would appear that although I have a credible, incoming "activityId" coming into the method, the way in which I'm passing it into my route / method is coming up short.

What am I doing wrong?

BTW: When I run this as my URL: companies/activities/5e8492c99c41674ce023f7f3

I get a good result.

So, the route and the service are sound, it's just the way I'm passing that activityId into the mix from my initial method that's bogus, correct?

What am I missing?
Node.jsJavaScript

Avatar of undefined
Last Comment
Chris Stanyon
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey Bruce,

Can't see anything obviously wrong with your code. Try building your url (in your showActivityForm) as a variable a console.log that:

let url = `/companies/activities/${activityId}`
console.log(url);
$.get(url, function(resp) {

Open in new window

More of a sanity check than anything else.

Also console.log from your route:

let activityId=req.params.activityId
console.log(acticityId)

Open in new window

and finally, console.log from your Activity service:

getOne(activityId) {
console.log(activityId);

Open in new window

Avatar of Bruce Gust
Bruce Gust
Flag of United States of America image

ASKER

Chris, I think I found something...

When I do this in my router code:

router.get('/companies/activities/:activityId', async(req, res)=> {
   try {
      //console.log(req.params.activityId);
      let activityId=req.params.activityId;
      console.log("routerId");
      console.log(activityId);

      let activity = await Activity.getOne(activityId);
      res.send(activity);
    } catch (err) {
        res.send(error('An unexpected error was encountered while trying to load your proposal. Please try again.'));
    }
});

...and I double check what I'm seeing as a potential problem in my activity.js service:

      getOne(activityId) {
         return new Promise((resolve, reject) => {
            console.log("here");
             console.log(activityId);

            let activity_Id = this._getId(activityId);
            this.model.findOne({ _id: activity_Id }, (err, res) => {
                if (err) { console.log(err); reject(err); }
                resolve(res);
            });
        });
    }

I get this:
routerId
5e84959c9c41674ce023f7f5"
here
5e84959c9c41674ce023f7f5"

My activityId is being presented to the "_getId" method with the activityId followed by double quotes. Where are they coming from?


ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Bruce Gust
Bruce Gust
Flag of United States of America image

ASKER

I found it!

It was coming from this:

<a href="#" style="float:right;"><i class="fas fa-fw fa-trash"></i></a><a href="#" class="note-link" data-prospect-id="{{ data._id }}" data-route="companies" data-company-name="{{ data.name|e('html_attr') }}" data-user-id="{{ (data.owner is empty?'undefined':data.owner._id) }}" data-activitId="{activity._id}}" data-toggle="tooltip" title="Edit Activity" data-activity-type="note" data-activityId="{{ activity._id }}" style="float:right;"><i class="fas fa-fw fa-pencil fa-pencil-alt"></i></a>

The part that I have in bold was originally, data-activity={{ activity._id }}"

I only had one set of double quotes.

So, that's fixed!

Since our last correspondence, I hard coded a reliable id into the method and I've been able to make decent amount of progress. I've got to be able to coordinate with the "select" in my form to it displays a "selected" value. I've got that question here:

https://www.experts-exchange.com/questions/29178560/How-can-I-included-a-selected-option-in-this-select.html 


Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey Bruce,

Nice find - that's what I was kinda getting at when I said look at the click event handler ;)
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo