What is the best way to access a particular property of an object?

Currently, I am successfully sending data to Mongo and storing user input information in the backend. In the console, an interceptor message confirms that the data is received from MongoDB. However, I am struggling to extract specific properties such as the user's email, photo title, and URL blob as individual data, rather than viewing it as a whole object in the console.

-- THIS IS IN MY VUE --

dohvatiObjavu(){
      
        this.objava = Objave.dohvati_objavu();

        console.log("Current post " + this.objava);
     
        }
}, 

-- THIS IS IN SERVICES --

let Objave = {
    async dohvati_objavu() {

        let response = await Service.get(/galerija)

        let data = response.data;

        console.log("Current posts in services: "+data.naslov)

            return {
                id: data._id,
                email: data.email,
                naslov: data.naslov,
                noviOpisSlike: data.noviOpisSlike,
                slika: data.slikaReference,

            }

    },
}

-- THIS IS IN BACKEND --

app.get ('/galerija', async (req , res) => {
let db = await connect();
let cursor = await db.collection('galerija').find();
let results = await cursor.toArray();

res.json(results);

});

-- MY CONSOLE --

https://i.sstatic.net/HEwBn.png

Answer №1

Objave.fetch_post(); is an asynchronous function, meaning it should be awaited within your Vue method fetchPost().

I have provided a simplified example below based on your code:

const Objave = {
  fetch_post: async function() {

    // Mock Service.get(/gallery) with Promise.resolve
    const data = await Promise.resolve({
      id: 'mockId',
      email: 'mockEmail',
      title: 'mockTitle',
      newImageDescription: 'mockNewImageDescription',
      image: 'mockImage',
    });

    return {
      id: data._id,
      email: data.email,
      title: data.title,
      newImageDescription: data.newImageDescription,
      image: data.imageReference
    }
  }
}

const MyVueComponent = class {
  post = undefined;

  // DOES NOT WORK
  fetchPost() {
    this.post = Objave.fetch_post();
    console.log("[fetchPost] Current post ", this.post);
  }

  // WORKS 
  async fetchPost2() {
    this.post = await Objave.fetch_post(); // <!-- await
    console.log("[fetchPost2] Current post ", this.post);
  }
}

const component = new MyVueComponent()
component.fetchPost();
component.fetchPost2();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase saved HTML content within an HTML page?

I have some HTML data that was saved from a text editor, <p style=\"font-size: 14px;text-align: justify;\"> <a href=\"https://www.xpertdox.com/disease-description/Chronic%20Kidney%20Disease\" style=\"background-color: tr ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

Encountered an issue during Karma unit testing of an Ionic App: the error message [ng:areq] indicates that the argument 'StockCtrl' is not recognized as a function and is

I've encountered an issue while trying to conduct unit testing on my ionic app. Despite checking previous queries, none of the given solutions seem to work for me. Any suggestions on what might be causing this error? The error message I'm receiv ...

What is the best way to initiate a local Node.js server specifically when launching a desktop Electron application?

I am looking to ensure that my node js server runs while my electron app is open. One method I have attempted is using the child_process module to execute a shell command as shown below: const {exec} = require('child_process') const startDBServ ...

What is the best way to store multiple values in local storage using useState in react?

Currently, I am exploring how to utilize multiple values in the useState hook and perform CRUD operations in local storage. Here is an example of my code: const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }]] // ...... ...

React: the props appear to be undefined when they should actually have a value

I have a requirement for my props in the children class to be an array of Event objects. Prior to using it in App.js, I am checking if the array is empty like this: function App() { class Event { constructor(id, title, date){ this.id = id; ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

What is the method for storing elements in localStorage within a ReactJs application?

Currently, I am working on learning react-redux and coding a new project. My goal is to implement a feature where clicking the Add Favorites button will push all column data to local storage. Despite reading numerous articles, none of them have provided ...

What methods can I use to ensure the headline remains fixed like the table headers?

I am currently working on creating sticky table headers. Below is an example showcasing my progress and what I am aiming to accomplish. Below is the script I discovered from another source. function makeTableHeadersSticky(tableId) { var thArr = $(tableId ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

Safari's anchor links tend to leap higher than necessary

One of the anchor links on my website is behaving strangely in Safari, both on iPhone and MacOS. Instead of scrolling to the correct position of the anchored div, it scrolls to a random location around 400-500px higher than it should be. All other anchor l ...

transmit FormData containing two files and a text message to the controller

I have encountered an issue while trying to send a FormData object containing text fields, an image file, and a PDF file to an action in the controller. Despite my efforts, the form data is not being sent to the action. I have checked for errors through br ...

Setting props to slot elements in VueJS: A comprehensive guide

Can props be assigned to slot elements? Example <script id="templ-container" type="text/x-template"> <div> <p>top</p> <slot class="borders"></slot> <p>bottom</p> </div> ...

Two AJAX requests sent with different URLs for success and failure responses

Hello there, I find myself in quite a pickle. I am dealing with an ajax request from select2 and have two different URLs to work with. How should I structure my events to handle success and failure scenarios, where if one URL fails, I can send a request ...

Styling with CSS: A guide to reducing paragraph margins within a div element

My current project involves using javascript to dynamically insert paragraphs inside a div element. Essentially, the script grabs the value entered into an input form when a button is clicked and adds it as a new paragraph within a specific div. However, I ...

Show off markdown formatting without the need for v-html

I run a unique type of platform that allows users to publish their own blog posts using a WYSIWYG editor, and then share them on the site. My top priority is to ensure security against XSS attacks, which is why I am looking for alternatives to using v-htm ...

Attempting to transfer elements from an iteration into a separate array

Currently, I am attempting to insert an associative array into an object that is empty. However, I keep encountering the following error message: An undefined property '#<Object>' cannot be read Here is the code snippet that I am testing: ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...