3

Long story short I'm creating a User model that needs to be able to have expiring subscriptions, and was wondering how to store them correctly using Sails. The kind of model I need is:

User : {

    ...

    subscriptions : [{
        artist : <association>,
        starts : {
            type : "date"
        },
        expires : {
            type : "date"
        }
    }]

    ...

I'm using MongoDB, and know this is possible, however it needs to be done through Sails.js' Waterline ORM. Would I have to use a separate "Subscription" Model that's associated to the users and artists?

1
  • Short answer: yes! you need a new, separate model for Subscription Commented Apr 8, 2015 at 16:49

1 Answer 1

2

It all depends on how you want to do queries against your subscriptions later.

SailsJS find method does not handle a way to say User.find({"subscriptions.expires">=today}) directly, if subscriptions is defined as an Array or a Collection.

If you define Subscription as a model, then you can make it a collection in your User model, referencing Subscription, and then you perform queries against Subscription, like Subscrition.find({'expires'>=somedate).

The drawback is that this creates a new collection that has the relationship between the two Models, you don't get an embedded object with all your data, if that is what you try to accomplish.

If you want it to be all in an embedded object, you can do it, but then you need to use the Waterline .native method, that allows you to send direct queries in MongoDB NodeJS driver form, as documented in Node.js MongoDB Driver API Documentation

It would be something like

User.native(function(err, collection) {
if (err) {
  return console.log(err);
} else {
  collection
    .find({
      'subscriptions.expires': {
        $gte: new Date(2012, 7, 14)
      }
    }, {
      'data': 1
    }, 0, 1)
    .toArray(function(err, subscriptions) {
      if (err) {
        return console.log(err);
      } else {
        if (subscriptions.length > 0) {
          // Do whatever here
        } else {
          return console.log('No subscriptions found');
        }

      }
    });
}
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.