The JSON field is missing from the GET response in mongoose

I am dealing with a JSON document (found in mongolab):

{
    "_id": {
        "$oid": "566e8673eb862d165fef7171"
    },
    "street": "Dizingof",
    "buildingNumber": 33,
    "apartmentNumber": 63,
    "beds": 3,
    "owner": {
        "_id": {
            "$oid": "564374944cb813541afc193a"
        },
        "local": {
            "password": "$2a$08$PtZrvLY7MWSi44gMDSjLJ.u4x.IOXIkRFZYfQhAwt.5vSIXpCYjX6",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9aab6b4bcbcb4b8b0b599beb4b8b0b5f7bab6b4">[email protected]</a>"
        },
        "__v": 0
    }
}

The schema defines the owner field as:

owner           :  {
                type: Schema.ObjectId,
                ref: 'User'
        }

However, when I make an http.get request to fetch the listing, the returned data is missing the owner field:

{
  "_id": "566e8673eb862d165fef7171",
  "street": "Dizingof",
  "buildingNumber": 33,
  "apartmentNumber": 63,
  "beds": 3,
  "imagesAndCount": [],
  "UsersAndQuestions": []
}

I need access to the owner field for HTML document manipulations but it's not there. Why could this be happening?

For reference, here is the relevant GET route in routes.js:

app.get('/api/listing/:street/:buildingNumber/:apartmentNumber', function (req, res) {
        Listing.findOne(
            {
                "street": req.params.street,
                "buildingNumber": req.params.buildingNumber,
                "apartmentNumber": req.params.apartmentNumber
            }
            , function (err, listing) {
                if (err) { return next(err); }
                res.json(listing);
            });
    });

Additionally, I populated the owner field like this:

var myUser = db.users.findOne()
db.listings.insert({"street" : "Dizingof", "buildingNumber" : 33, "apartmentNumber" : 63, "beds": 3, "owner": myUser})

Answer №1

Your problem lies here

holder :{
    category: Schema.ObjectId,
    reference: 'User'
}

Mongoose is anticipating a link to a document, which can then be filled using populate (remember, this only works in arrays of types) so it's not being retrieved as part of your query.

If you are utilizing version 4.2 of mongoose, you could try something similar to this:

http://mongoosejs.com/docs/subdocs.html#altsyntax

var ownerSchema= new Schema({ label: 'string', additionalInfo: 'string' });

var parentSchema = new Schema({
  holder: ownerSchema
});

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 are some strategies for retrieving a greater quantity of data from the Stack Exchange API?

When using the Stack Exchange API, only 30 items are returned per request. To retrieve 4500 records, I utilized a for loop as shown below: import requests complete_data=[] for i in range (150): response = requests.get("https://api.stackexchange.com/2. ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

issues with ionic routing, malfunctioning

I'm completely new to Ionic and currently working on an application. However, I've hit a roadblock when it comes to routing between pages using tabs. I am struggling to grasp how the control flows into $stateProvider.state(...) and have encounter ...

Revamp the HTML page by automatically refreshing labels upon every Get request

My HTML webpage requires real-time updates for one or more labels. To achieve this, I have incorporated CSS and JS animations into the design. Currently, I am utilizing Flask to handle all the calls. I face a challenge where I need to consistently update ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Encountering issues with saving to MongoDB via Mongoose when using ObjectId as a string

I am encountering a validation error while attempting to save my object to MongoDB using Mongoose/Joigoose. The schema is for a simple Group object with a reference to a parent Group's ObjectId (parent_group). Here is the specific error message: Vali ...

Avoiding errors caused by higher order array methods

Is there a way to avoid errors when filtering data? The function below may encounter issues at conversationMember.Name.toLowerCase() if conversationMember is not present. This function is part of a computed property in a Vue application. Feel free to ask ...

Tips for locating a value that differs from an item in a v-autocomplete box

I am using a v-autocomplete component: <v-autocomplete v-model="fromPrice" :items="listOfFromItems" dense solo label="from" hide-detail ...

Convert JSON objects into arrays with multiple dimensions

What is the best way to retrieve the Object[][] from a JSONObject? Below is the code snippet I am currently using to accomplish this task: Object[][] object2dArray= {{"String"},{315296487},{142736598.342},{"text"}}; JSONObject json = new JSONObject(); js ...

What is the best way to implement an automatic logout feature in PHP?

I develop websites with login/logout functionality. Whenever a link or button is clicked on the website, I use an ajax function to verify the user's login status and automatically log them out if their session has expired. The logout function also up ...

Sending a JavaScript variable to a Ruby on Rails controller for passing it to an API for further processing

My index.html file contains a Google API map implementation. <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: ...

Exclude objects with similar ids using a method other than JavaScript's filter()

I have a list of students who need to receive medication multiple times throughout the day. The challenge is to filter the array to track how many times each student receives the same medication. The list includes three different students and repeats the s ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

How can I trigger an AJAX request when the value in a dropdown menu is changed?

index.php <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <a href='one.php' class='ajax'>One</a> <a href='two.php' ...

Is hard coding permissions in the frontend considered an effective approach?

I'm in the process of creating an inventory management system that allows admin users to adjust permissions for other employees. Some permissions rely on others to function properly, and I need to display different names for certain permissions on the ...

Encountered an issue with Nextjs dynamic routes and static pages where the error message states that the `paths` variable needs to be an

I have been following the official Next.js guide on generating statically generated pages with dynamic routes (Nextjs - Dynamic Routes). However, I am facing an issue when trying to generate pages with fetched data. The error message I am receiving is as f ...

Transmitting data object via AJAX request to a WebMethod

I am attempting to pass a JSON object to a C# method and receive a different JSON object in return. The object is initially created in JavaScript: lottery = { TotalValue: totalValue, Players: txtPlayers.value, TicketPrice: txt ...

Serializing a C character array (char*) into JSON format

Can a C char array (char*) be encoded in JSON for transmission via a TCP socket? If yes, how can this be done and which JSON library would be recommended for simplicity? Appreciate it, ...