Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' model. My problem is that I am unable to retrieve the 'country_name' attribute from the 'Country' model when displaying all the properties of a singer. I'm not sure how to accomplish this. Below is my code: My 'Singer' model

 module.exports = {

attributes: {
singer_name:{
    type: 'string',
    required: true,
    size: 50
},
singer_realname:{
    type: 'string',
    size: 50
},
singer_gender:{
    type: 'string',
    enum: ['Male', 'Female'],
    defaultsTo: 'Male'
},
singer_brithday:{
    type: 'int'
},
singer_image:{
    type: 'string'
},
singer_description:{
    type: 'string'
},
singer_country:{
    type: 'string'
}

}
};

My 'Country' model:

  module.exports = {

attributes: {
country_name: {
    type: 'string'  
}
}
};

My method for displaying singer's properties:

index: function(req, res, next){
    Singer.find().exec(function foundSinger(err, singerObj){
        if(err) return next(err);   
            res.view({
                singers: singerObj,
        });     
    });
},

I am using MongoDB as my database, and I am working with sails beta 0.10 rc8. Any help would be greatly appreciated. Thank you.

Answer №1

musician_country:{
    model: 'Country'
}

Musician.find().populate('musician_country').exec(function foundMusician(err, musicianObj){
    if(err) return next(err);   
        res.view({
            musicians: musicianObj,
    });     
});

Answer №2

There are multiple factors at play, but if you have a one-to-one association, then your singer_country attribute should look something like this:

singer_country: {model: 'country'}

https://example.com/associations

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

Jquery and CSS3 come together in the immersive 3D exhibit chamber

Recently, I stumbled upon an amazing 3D image gallery example created using jQuery and CSS3. http://tympanus.net/codrops/2013/01/15/3d-image-gallery-room/ Excited by the concept, I attempted to incorporate a zoom effect (triggered every time a user clic ...

Field for user input featuring a button to remove the entry

I am attempting to add a close icon to a bootstrap 3 input field, positioned on the top right of the input. Here is what I have tried so far: https://jsfiddle.net/8konLjur/ However, there are two issues with this approach: The placement of the × ...

What code can I use to prompt clients to refresh JavaScript files automatically?

We are experiencing an issue where, even after pushing out updates with new JavaScript files, client browsers continue to use the cached version of the file and do not display the latest changes. While we can advise users to perform a ctrlF5 refresh during ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Trigger a callback in ASP.NET's CallbackPanel using JavaScript every 10 seconds

I am attempting to automatically trigger the callback of a CallbackPanel using JavaScript in my WebFormUserControl every 10 seconds. While I can trigger it with an ASPxButton and ClientSideEvents, my ultimate aim is to have it start automatically every 10 ...

Has anybody successfully implemented the danfojs-node package on an Apple M1 chip?

I encountered an issue when trying to use danfojs-node on a Mac with an M1 chip - it kept crashing due to TensorFlow. I'm curious if anyone has managed to successfully integrate the npm package from this link (https://www.npmjs.com/package/danfojs-nod ...

Whenever I attempt to incorporate the 'var' keyword within a for loop alongside setTimeOut, I encounter unusual output

Here's the code snippet I'm working with: for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log(i); }, 1000); } I'm confused about the output of this code. When I run it, I see the number 6 printed in the c ...

Creating an input field within a basic jQuery dialog box is not possible

Can anyone assist me in adding an input box to my dialog box? I am working with jquery-ui.js. Here is the code I currently have: $(document).on("click",".savebtn",function(). { var id = $(this).attr("id"); $.dialog({ ...

Transmitting arguments within an instance method in Mongodb using Mongoose

Is there a way to pass a parameter inside an instance method in JavaScript? var User = new Schema({ following: [{ type: Schema.Types.ObjectId, ref: 'User' }], followers: [{ type: Schema.Types.ObjectId, ref: 'User' }] }); User. ...

Issue encountered: Django pymongo update_many Cannot traverse the element ({x: []}) using the part (y) of (x.y)

My data collection contains sample documents structured like this: [ { "_id": { "$oid": "64b28bafb2ea43dd940b920d" }, "title": "Village Libraries", "keywords": { &quo ...

Divide a string into separate numbers using JavaScript

This snippet of code is designed to search the table #operations for all instances of <td> elements with the dynamic class ".fuel "+ACID: let k = 0; let ac_fuel = 0; parsed.data.forEach(arrayWithinData => { let ACID = parsed.data[k][0]; ...

Using JavaScript to display a selection of objects from an array: showcasing x out of x items

What is the most efficient method for sorting or querying an array of objects using JavaScript? For example, how can I retrieve only the first two objects, followed by the next two, or obtain 5 objects starting from the 5th position? Which specific functi ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

How can I ensure that the ons-scroller stays at the bottom when writing a JavaScript code in Onsen UI?

How can I ensure the ons-scroller stays at the bottom when writing JavaScript? This is the code I am using: <ons-page> <ons-toolbar> <div class="left"><ons-back-button>Return</ons-back-butto ...

Implement a mouseover event on the axis label using D3.js and JavaScript

Is it possible to trigger a mouseover event on the y-axis label in a chart? For instance, let's say we have a scatter plot with labels "area1", "area2", and "area3" on the y-axis. When a user hovers over the label "area1", a tooltip should appear disp ...

Establishing a distinct index in MongoDB based on specific criteria

Recently, I've been delving into mongodb and stumbled upon the concept of imposing unique constraints in mongodb using the createIndex with a unique field set to true. This ensures that a specific field in the index remains unique across the entire da ...

"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below: <select ng-model="data.company" ng-options="company as company.name for company in companies"></select> $scope.compani ...

What is the process for locating a newly created user in MongoDB when utilizing the "register" function within the "passport" module of a NodeJS application?

After following this code to create a new user: try { User.register(new User({username : email , email : email , password : password}), password, (err , user) => { if (err) { console.log("error happened!" , err); ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

Tips for positioning input fields and labels in both horizontal and vertical alignment

Below is the HTML code, and I want the tags to look like this: label1: input1 label2: input2 label3: input3 Instead, it currently looks like this: label1: input1 How can I modify the HTML to achieve the desired format? HTML: <div class=" ...