Abid Rakhmansyah
Abid Rakhmansyah

Reputation: 966

Get value in Object of Mongoose result

I've query like this const result = await Form.findOne({ _id: req.params.id });
And here is the result of my query:

{ _id: 5a8ea110d7371b7e5040d5c9,
  _user: 5a5c277f8d82ba3644b971c2,
  formDate: 2018-02-22T10:53:04.579Z,
  formElement: 
   { formName: 'Vanilla Form',
     pixel: '23423325',
     fieldRows: [ [Object], [Object] ] },
  formStyle: 
   { globalColor: [ [Object], [Object], [Object] ],
     elementSizing: 'medium',
     elementStyle: 'radius',
     fontFace: 'Open Sans',
     fontSize: { label: '15', button: '15' } },
  __v: 0,
  status: true }

I'm trying to get pixel like this console.log(result.formElement.pixel)
But, when i trying to get the value of pixel, it return undefined.
What's wrong?

Update
Here is my code:

app.get("/view/:id", async (req, res) => {
    const result = await Form.findOne({ _id: req.params.id });
    console.log(result);
    console.log(result.formDate); //return 2018-02-22T10:53:04.579Z,
    console.log(result.formElement.pixel) //return undefined
    // res.render("form", {
    //  result
    // });
});

I've try to edit my code without using async instead using Promise, but it also return undefined

Upvotes: 1

Views: 100

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 10071

you need to use exec() function, It returns promise.

app.get("/view/:id", async (req, res) => {
    let result = await Form.findOne({ _id: req.params.id }).exec();
    result = JSON.parse(JSON.stringify(result));
    console.log(result);
    console.log(result.formDate); //return 2018-02-22T10:53:04.579Z,
    console.log(result.formElement.pixel) //return 23423325
    // res.render("form", {
    //  result
    // });
});

Upvotes: 2

iamsellek
iamsellek

Reputation: 136

You're gonna need to do some digging here. Add some more console.logs to debug what is actually going on. For starters, I'd recommend printing out result to see what it actually is. My first guess is that you're trying to print result before the await finishes? I'm not sure, as I don't know exactly when you're trying to print anything out without seeing your code.

Upvotes: 2

Related Questions