Steps for adding an additional field to a join in Sails JS

Hello everyone, I am new to Sails js and mongoDB and feeling a bit lost at the moment.

I have set up two models with a many-to-many relationship:

User.js

module.exports = {
  attributes: {
    username: 'STRING',
    password: 'STRING',
    doors:{
        collection: 'door',
        via: 'users',
    }
  }
};

and Door.js

module.exports = {
  attributes: {
    name: 'STRING',
    users:{
        collection: 'user',
        via: 'doors'
    }
  }
};

Everything is working as expected, I can create a user and a door and link them together. However, I would like to include another field in the association - an expiry date (for example, when the user's access to a specific door expires).

Any suggestions on how I can achieve this?

Answer №1

If you are looking to establish a many-to-many relationship through association, it is important to note that this feature is not officially supported yet.

However, there is a workaround available for manual implementation.

In the following example, retrieving all doors for a user and vice versa may be slightly more complex as it requires an additional lookup. Nonetheless, you can achieve this by following the setup outlined below:

UserDoors
    .find()
    .where({expires:{'<':new Date()}})
    .populate('doors')
    .populate('users')
    .exec(/*....*/)

Your model configurations:

User.js

module.exports = {
  attributes: {
    username: 'STRING',
    password: 'STRING',
    doors:{
        collection: 'userDoors',
        via: 'users',
    }
  }
};


userDoors.js
module.exports = {
  attributes: {
    doors:{
        model: 'door'
    },
    users:{
        model: 'user'
    },
    expires: 'datetime'   
  }
};



and Door.js

module.exports = {
  attributes: {
    name: 'STRING',
    users:{
        collection: 'userDoors',
        via: 'doors'
    }
  }
};

You can also search for sails.js many to many through on Google for further guidance on this topic.

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

Transmit information to firebase using HttpClient

Seeking assistance on updating Firebase data (Realtime Database) in a specific table without overwriting it. The current code I have is causing the table [TB_MyProfile_Composite] to be overwritten instead of updated. Here is the code snippet for updating ...

Cause a malfunction in the triggering function of jQuery

$(document).ready(function(){ jQuery("#but1").bind("click",function(e){ alert(e.name); }); jQuery("#but1").trigger({name:'Dmy', surname:'My'}); }); The information doesn't seem to be getting passed correctly a ...

Choosing the number of items for each cartItem in KnockoutJS: A comprehensive guide

Greetings! I am new to using knockout and I am attempting to automatically select the quantity for each item in my cart from a dropdown menu. Below is the code I have written: VIEW <div data-bind="foreach: cartItems"> <h3 data-bind="text: ful ...

Setting up MongoDb on a Lubuntu system

I am having trouble installing MongoDD on my Lubuntu system by following the official instructions for Ubuntu provided here. When I attempt to execute this command: sudo apt-get install -y mongodb-org An error occurs and I receive the following message: ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Selecting an option in Javascript when the .selectedIndex property is unpredictable

My current challenge involves using a mix of applescript and javascript to choose an option from a dropdown select menu without knowing the .selectedIndex in advance. tell application "Safari" activate tell document 1 do JavaScript "document.getElemen ...

Is there a foolproof way to determine when a dialogue box pops up on

I'm currently building an electron app using vue and Vuetify. I am able to create a modal using dialog, but I want to be able to modify certain elements within the dialog after it is displayed. When using $refs, I cannot find the element before the d ...

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

I am interested in implementing a "slide up" effect for the "slide menu" when it loses focus

When I focus out of the asmenu class, I attempt to trigger a 'slide up' effect. However, if I select two checkboxes from the child elements within the asmenu class, the focusout event is still triggered. Ideally, I would like the 'slide up& ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

Validating Presence of a Value in an Array Object Using AngularJS

var SelectedOptionId = 957; $scope.array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}] Is there a method to verify the existence of a value within an array of objects like this using Angular and underscore? I've att ...

What is the best way to eliminate the time component from an object in JavaScript?

I have a task to strip the time information from a specific property in my object. To achieve this, I am checking if any timestamps are present in the property value by using an index. Here is the initial input: input [ { "S": "Charge Interest Agai ...

Steps for raising a unique error in an asynchronous callout

As I work on making async API callouts, there might be a need to throw custom errors based on the outcome. Also, part of this process involves deleting objects from S3. try { await s3.deleteObject(bucketParams); //Since S3 API does not provide ...

Error 404: Image not found in webpack

Can anyone help me with importing an image using the web pack configuration? After running yarn build on my app, I encountered an error in the console. How can I import an image from the assets/public folder to the dashboard file? (refer to the attached i ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

Combining PouchDB with Vue.js for seamless integration

Has anyone successfully integrated PouchDB / vue-pouch-db into a Vue.js application before? I encountered an error when attempting to define the PouchDB database. Here are the definitions I tried: import PouchDB from 'pouchDB' or import PouchDB ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

How can I insert a Vue component into the DOM just like I would with an HTML element?

Currently, I have developed an alert component that is utilized in my project. For example, it can be called using <AlertComponent message="message" />. In my main App.vue file, I have a method that handles incoming messages and I would li ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...