GithubHelp home page GithubHelp logo

balderdashy / waterline-docs Goto Github PK

View Code? Open in Web Editor NEW
452.0 27.0 163.0 169 KB

WARNING: The content in this repo is out of date! See https://github.com/balderdashy/sails-docs for the most up-to-date documentation

waterline-docs's Introduction

Waterline Documentation

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//  ██╗    ██╗ █████╗ ██████╗ ███╗   ██╗██╗███╗   ██╗ ██████╗ ██╗
//  ██║    ██║██╔══██╗██╔══██╗████╗  ██║██║████╗  ██║██╔════╝ ██║
//  ██║ █╗ ██║███████║██████╔╝██╔██╗ ██║██║██╔██╗ ██║██║  ███╗██║
//  ██║███╗██║██╔══██║██╔══██╗██║╚██╗██║██║██║╚██╗██║██║   ██║╚═╝
//  ╚███╔███╔╝██║  ██║██║  ██║██║ ╚████║██║██║ ╚████║╚██████╔╝██╗
//   ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝
//                                                               
// WARNING: The content in this repo is out of date!
//
// This content has only been left here to try and maintain the quality of older search engine links.
// Please be sure and visit the appropriate link from the outline below for the most recent and up-to-date docs.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

Table of Contents

The Waterline documentation now lives in the Sails documentation. These links will bring you to the applicable doc pages on the Sails website.

Supported Adapters

A list of officially supported adapters can be found here.

Community Adapters

A list of community adapters can be found here.

Help / Questions

If you're unsure or could use some advice, click here.

waterline-docs's People

Contributors

akulnurislam avatar blamy avatar cshenoy avatar darth-cheney avatar ddelrio1986 avatar devinivy avatar dmarcelino avatar dtoubelis avatar eddieajau avatar evanburchard avatar globegitter avatar hderms avatar jgod avatar kevinob11 avatar luislobo avatar mhvis avatar mikermcneil avatar mohitmehta11 avatar moisesbaddini avatar mphasize avatar particlebanana avatar rachaelshaw avatar tagraves avatar tjwebb avatar waynecheah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

waterline-docs's Issues

databases in mongodb and mysql are not working properly together

If there are two databases one in mongodb and other in mysql and now we want to associate the two databases together then the queries doesn't give the expected output as it gives on databases in pure mysql or mongodb.
eg.User.find()
.populate('pets')
.exec(function(err, users) {});
on applying this function where user is in mongodb while pets is in mysql then the function doesn't club the pets according to users id's .Please look into this

extra fields on many to many relationships join table (feature request)

I didn't find solution in documentation so I suppose this feature is not implemented.
It's a widely used approach when we save extra data with relation.
Like quantity for sold products in order-product relation.
Like expiration on user-post-ban. etc. etc.

I'd also appreciate any help on how to do it manually.
I've even created a question, but no luck with a proper answer yet.

document that save() can clobber values

say you have two threads which both have a User object in memory. one updates the email, the other updates the phone number. both call save(). this turns into

UPDATE users set email=newemail, phonenumber=oldphonenumber, ...
UPDATE users set email=oldemail, phonenumber=newnumber, ...

both threads believe they've saved the new value on the object, however, one of the updates got clobbered by the other one.

probably no plan to fix this behavior, might at least want to document it & explain that you probably want to do an UPDATE w/ only the affected property(ies) if you care about the consistency of your data.

Refactor associations

I'd like to refactor the "association" doc page into separate pages for each type of association, and make sure the information is in line with the Sails docs at the same time. Does that sound reasonable?

Many to Many add method failing ( object is not a function )

I have 2 models Groups and Users as below :-

Groups.js

/**
* Groups.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {

  attributes: {
     id:{
        type: 'integer',
        primaryKey: true,
        unique: true,
        autoIncrement: true
     },
     group_name:{
        type: 'string',
        required: true
     },
     group_description:{
        type: 'text'
     },
     group_status:{
        type: 'string',
        enum: ['Active','Inactive'],
        defaultsTo: 'Active'
     },
     thirdparty:{
      collection: 'thirdparty',
      via: 'groups'
     },
     users:{
        collection: 'users',
        via: 'groups'
     },
     tickets:{
        collection: 'tickets',
        via: 'groups',
      dominant: true
     }
  }
};

Users

module.exports = {

  attributes: {
     id:{
        type: 'integer',
        primaryKey: true,
        unique: true,
        autoIncrement: true
     },
     username: {
        required: true,
      type:'string',
      alpha: true,
        unique: true
     },
     email_address:{
        required: true,
      type: 'email',
        unique: true
     },
     password:{
      required: true,
      type: 'string'
     },
     alternate_email_address:{
        type: 'email'
     },
     contact_no:{
        type: 'string',
      numeric: true
     },
     account_status:{
        type: 'string',
        enum: ['Pending','Active','Inactive','Suspended'],
        defaultsTo: 'Pending'
     },
     is_verified:{
        type: 'boolean',
        defaultsTo: false
     },
     verification_token:{
        type: 'string'
     },
     groups:{
        collection: 'groups',
        via: 'users'
     }
  }
}

Inside my User controller , i want to associate the user i am going to create with an existing group

Groups.findOne(1).exec(function(err,group){
    if(err){
        return 
    }
    if(group){
        Users.create(/*somedata*/,function(err,success){
            if(success){
                group.users.add(success.id);
                group.save();
            }
        });
    }
});

And it is returning

TypeError: object is not a function
  at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/schema.js:151:44
  at fn (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/callbacksRunner.js:78:5)

"Many-to-Many Associations" vs. "Many-to-Many Through Associations"

I think it's unclear how Many-to-Many Associations differentiates from Many-to-Many Through Associations

...
Many-to-Many Associations
Waterline will look at your models and if it finds that two models both have collection attributes that point to each other, it will automatically build up a join table for you.
...

...
Many-to-Many Through Associations
Many-to-Many through associations behave the same way as many-to-many associations with the exception of the join table being automatically created for you. This allows you to attach additional attributes onto the relationship inside of the join table.
...

What i need is "additional attributes onto the relationship inside of the join table" as described in the "Through Associations". Yet both parts f the documentation are saying the join table is created automatically.
Although I guess "Through Associations" is trying to say something like

... with the exception of the join table NOT being automatically created for you...

Apart from the "coming soon" in the documentation, is this feature already implemented, and the documentation is "coming soon", or does "coming soon" refer to the feature itself?

Add documentation for loading collections and initializing waterline

Adapters and connections configuration info is missing here. Also need to document how to extend and load model definitions. Basically, we need to document how to initialize waterline, drawing all the necessary connections between adapters, connections, and model definitions.

Example wrong for beforeValidate

The example for beforeValidate assumes that Probable_suspects is exposed globally, as it would be in Sails. However, this is not the case for Waterline, but it does lead me to ask can we expose some API to be able to get other collections whilst in the life-cycle hooks.

The immediate problem is how to correct the docs. I guess this will require a note to say that the application developer needed to expose a global for the model in the bootstrap code (I actually dislike polluting the global namespace in this way).

And/or we can solve it by deciding that the example use-case is useful and it need to lead to a code fix?

For example, something like this would be ideal:

  beforeValidate: function(citizen_record, next){
    var Probable_suspects = this.getCollection('Probable_suspects');

    Probable_suspects.findOne(citizen_record.citizen_id).exec(function(err, suspect) {
      if(err) return next(err);
      if(!suspect) return next(new Error('This citizen is not a suspect'));
      next();
    });
  }

Thanks in advance.

Model Definition and Custom Model Attribute Propertiy

I'm trying to get the model schema, so far I'm using the undocumented Model.defintion. I want to pass the schema to the frontend but of course I want to strip all the sensitive attributes.

So I'm doing this by defining a custom model attribute property public:

attributes: {
    name        : { type: 'string', unique: true, public: true },
    shortname   : { type: 'email',  unique: true, public: true },
    component   : { type: 'email',  unique: true },
  }

I'm then trying to exclude the nonpublic attributes that I will pass to the client with

function modelDefinition(model) {
    var fullDef = _.clone(model["definition"], true); // deep cloning
    var filteredDef = _.pick(fullDef, function(prop) {
        prop.public == true;
    });
    return filteredDef;
};

Also in Sails I have added this to config/models.js

validations: {
    ignoreProperties: [ 'public']
}

But it seems that when I grab the model schema with var fullDef = _.clone(model["definition"], true); the public property doesn't exist for any field. Is it a reserved word or I am doing something wrong?
What are the drawback of using the model.definition? Is it undocumented for a good reasons? Meaning I shouldn't use it? (why?)

Thanks

Multi-column association / condition

I'm porting our api from yii to sails.js. In the Yii model for "Project" I have a 'relation' to "Comment" as follows:

    public function relations() {
        return array(
            'comments' => array( self::HAS_MANY, 'Comment', 'obj_id', 'condition'=>'obj = "Project" AND comments.status='.Comment::STATUS_APPROVED, 'order'=>'comments.create_time DESC'),
            'commentCount' => array(self::STAT, 'Comment', 'obj_id', 'condition'=>'obj = "Project" AND status='.Comment::STATUS_APPROVED),
        );
    }

How can I model this in sails.js?

I have created a model attribute function

    comments: function( cb ) {
        Comment.find({ obj: "Project", obj_id: this.id }).exec( function(err, list) {
            cb( err, list );
        });
    }

... but it should be possible via associations... :/
Is there any documentation on this?

Sails deleted/drops all our collection data in migrate:alter mode

I wanted to understand why migrate:alter is designed in way that it first deletes the collection and then creates the collection and inserts all the previous data in it.

I somehow used migrate:alter in models on our production data and we lost all our data :(. Are there NO ways to recover that lost data?

Could you please explain the exact reason apart from mentioning just use 'migrate:safe' ?

Look forward for an early reply

Document model definition option: `ignoreProperties`

ignoreProperties are defined in the adapter's adapter.js like:

// These properties should be ignored in Waterline validations
validations: {
  ignoreProperties: [ 'async', 'special']
}

would allow:

attributes: {
        email: {
          type: 'email',
          special: true
        },
        cousins: {
          collection: 'related',
          via: 'property',
          async: true
        }
}

to be accepted by waterline without throwing errors.

Full details on balderdashy/waterline#482.

@mphasize, I stumbled upon ignoreProperties (which I had no knowledge of) while doing a code change. Can you possibly write a few words about it in models.md? Thanks! 😃

Sails service returns MongoDb results when no Waterline associations exist but then fails when they DO exist..!

I'm building a sails.js api with MongoDb as my db.
Sails with waterline
Those are my models (simplified just for the sake of this question):

models/Passport.js simplified:

identifier: {
      type: 'string'
 },

owner: {
      model: 'User',
      required: true
 },

models/User.js simplified:

username: {
        type: 'string',
        unique: true
 },
passports: {
        collection: 'Passport',
        via: 'owner'
}

_The problem_

In a sails.js service login function I first try to get the user by a username from the User collection.

sails.models.user.findOne({username: 'demo'}).exec(function onExec(error, user)      {
    user; //contains user info
}

So far so good.

Then when the user is fetched (which is successfull), I grab his user.id and try to fetch his passport from the Passport collection.

sails.models.passport.findOne({owner:user.id}).exec(function onExec(error, passp) {
    if(passp==undefined)    //puppies dying in this line!!!!
        throw new Error('Can't find this passport');
    }
}

The returned passp object is undefined.
What... WHY?

Additional info:

Running > db.passport.find({owner:"theCorrectUserId"}) in my mongo shell DOES return the correct passport thus its not a matter of an incorrect id, and also, running :

sails.models.passport.find().exec(function onExec(error, passports) {
    passports; //does contain all my passports
}

does contain all my passports. Thus its not a programming error either!

Aha moment:

What I've found over hours of banging my head on the wall is that _removing the association_ and thus making my models like so:

models/Passport.js simplified:

identifier: {
      type: 'string'
 },

owner: {
      type: 'string'
      required: true
 }

models/User.js simplified:

username: {
        type: 'string',
        unique: true
 }

does solve the problem, and makes my passp object fetch the correct data..

Am I using Waterline associations wrong? But then why does it work in mongo shell when the association exists?

Do I even need associations since I'm using 2 different queries in my service? What about performance?

Thank you..!

What does the 'alias' of an attribute do?

When testing, I noticed that my associations were being given an 'alias' attribute in the schema when using localDisk. Can this be used in the attribute definitions? E.g. my model has a field 'parentID' in the live (SQL) schema, but I want to refer to the association as 'parent', can I define my attribute with an alias?

Example:

// models/Comment.js
module.exports = {
  attributes: {
    ...
    parentId: {
      model: 'comment',
      alias: 'parent'
    },
    ...
  },
  ...
};

If not, what is this for?

Need more query examples for associations

If an object has an associated collection, it is not clear how (or even if its possible) to query into that associated object stuff.

Pet has an Owner
Owner has an emailAddress

How do I select all of the Pets whose owner has an emailAddress = "[email protected]"

While its easy to do 2 queries to accomplish this:

  1. Find the owner who has an emailAddress = "[email protected]" and get that persons id
  2. Find all Pets who have the id from query 1

It seems that there would be a better syntax for this:

Pet.find({ "owner.emailAddress" : "[email protected]" })

Now whether or not this is internally optimized or just syntactic sugar doesn't matter, its much easier to read and write.

where query on a Many-to-many association

Let's say I have a many to many association like below.

An user can own many pets and a pet can be owned by many users.
(I changed the table names to user and pet to go in line with the documentation)

var User = {
  attributes: {
    pets: {
      collection: 'Pet',
      via: 'ownedBy',
      dominant: true
    }
}

var Pet = {
  attributes: {
    ownedBy: {
      collection: 'User',
      via: 'pets',
      dominant: true
    }
  }
};

I want to get all pets owned by a certain user. I tried a query like below. My postgresql db returns an error complaining Pet.ownedBy column doesn't exist.

Pet.find()
  .where({
    ownedBy: userId
  })

waterline collection error

i'm building my models and when lifting sails, i got this error ! any idea?
/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:82
throw new Error('Trying to access a collection ' + collection + ' that is
^
Error: Trying to access a collection commerce that is not defined.
at ForeignKeys.findPrimaryKey (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:82:11)
at ForeignKeys.replaceKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:53:27)
at new ForeignKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:30:10)
at new module.exports (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema.js:30:17)
at Waterline.initialize (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline.js:106:17)
at buildORM (/usr/local/lib/node_modules/sails/lib/hooks/orm/build-orm.js:48:15)
at Array.async.auto.instantiatedCollections as 1

Is there a way i can create a collection at runtime ?

What I've understood, sails binds collection with its Models. Is there a way i can create a collection on runtime. What i want to do is create a different collection for each user. something like (user_12345).

I've tried waterline also, it allows me to query collections for CRUD operation. but I couldn't understand how to create a new collection using sails-mongo or waterline library. Please help.

how to sepcify the return fields

I want return only the name field by applying a projection to a waterline query:

Model.find({ where: { age: { '<': 30 } }, select: ['name'] })

but it still return all of the fields。

TODO: Add technical specification for Waterline object configuration.

Need to add a page for the details of the configuration of a new Waterline object going into more depth that the "getting started" information. Needs to outline the purpose and use of the adapters, connections and, in particular, defaults for models properties of the configuration.

Many to many through add failed

Whenever i am trying to add Many to Many through association it fails with this message.

/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/model/lib/associationMethods/add.js:279
var associationKey = collectionAttributes.attributes[attribute.on].via;
TypeError: Cannot read property 'via' of undefined
  at [object Object].Add.createManyToMany (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/model/lib/associationMethods/add.js:279:69)

Here goes my models

Properties.js

module.exports = {
  attributes: {
    id: {
      type: 'integer',
      primaryKey: true,
      autoIncrement: true
    },
    owners:{
      collection: "contacts",
      via: "properties",
      through: 'propertyowners'
    }
  }
};

Contacts.js

module.exports = {
  attributes: {
    id: {
      type: 'integer',
      primaryKey: true,
      autoIncrement: true
    },
    username:{
      type:'string',
      unique: true
    },
    properties:{
      collection:"properties",
      via: "owners",
      through: 'propertyowners'
    }
  }
};

PropertyOwners.js

module.exports = {
  tableName: 'property_owners',
  tables: ['contacts', 'properties'],
  junctionTable: true,
  attributes: {
     id: {
      primaryKey: true,
      autoIncrement: true,
      type: 'integer'
    },
    properties_ref:{
      columnName: 'property_id',
      type: 'integer',
      foreignKey: true,
      references: 'properties',
      on: 'id',
      via: 'contacts_ref',
      groupBy: 'properties'
    },
    contacts_ref: {
      columnName: 'contact_id',
      type: 'integer',
      foreignKey: true,
      references: 'contacts',
      on: 'id',
      via: 'properties_ref',
      groupBy: 'contacts'
    },
    owner_from_date:{
      type: 'datetime'
    },
    owner_till_date:{
      type: 'datetime'
    },
    is_still_owner:{
      type: 'boolean',
      defaultsTo: true
    }
  }
};

No idea what is going wrong

Question about associations and populate

I like populate but I encounter a scenario when I need it and is not possible.

When you create a new model and this model have a association (whatever kind of association) the create method return the new object but not return only with the FK of the association. So populate doesn't work when you created news instances.

I fixed it doing a find of the new instance with populate and return it, but I'm think that is not efficient.

Is it possible any better solution?

In my particular case, I need that the return contain the model association values (in HTTP and sockets)

My solution:

# Create new instance of model using data from params
  Model.create(data).populateAll().exec (err, newInstance) ->

    # Differentiate between waterline-originated validation errors
    # and serious underlying issues. Respond with badRequest if a
    # validation error is encountered, w/ validation info.
    return res.negotiate(err)  if err

    # Use find method to return the model for the populate option
    Model.findOne(newInstance.id).populateAll().exec (err, newInstance) ->

      # If we have the pubsub hook, use the model class's publish method
      # to notify all subscribers about the created item
      if req._sails.hooks.pubsub
        if req.isSocket
          Model.subscribe req, newInstance
          Model.introduce newInstance
        Model.publishCreate newInstance, not req.options.mirror and req

      # Send JSONP-friendly response if it's supported
      # (HTTP 201: Created)

      # Change the id for user.email
      res.status 201
      res.ok newInstance

How to find entity using their associate's attribute?

Please help me My issue describe as follow

  1. User Entity

var User = Waterline.Collection.extend({

identity: 'user',
connection: 'local-postgresql',

attributes: {
firstName: 'string',
lastName: 'string',

// Add a reference to Pet
pet: {
  model: 'pet'
}

}
});

  1. Pet Entity

var Pet = Waterline.Collection.extend({

identity: 'pet',
connection: 'local-postgresql',

attributes: {
breed: 'string',
type: 'string',
name: 'string',

// Add a reference to User
user: {
  model: 'user'
}

}
});

These entities are associated with each other.
Now I want to find User entity using attribute of pet (i.e name).
How should be query for this situation ?

what are the query modifiers? I can do the write up if I have a list

Not sure where the line is between "query modifier" and "criteria". Might be useful to make the distinction on the query methods and query modifier pages.

Is this the list? Is everything that isn't attribute name a query modifier? Did I miss any?

where
limit
skip
sort
paginate
groupBy
sum
max
min
average
or?

Validate associations

In my case, a message has one or more contacts. I expected association validated when i have

// input
var msg = {
    userId: req.user.id,
    dateTime: new Date(),
    sender: data.sender || "",
    message: data.content || "",
    type: "sent",
    contacts: (data.recipients || "").split(/[\s,]+/)
};
// validating
Message.validate(msg, function(err){
    if(err) return reject(err);
    resolve(true);
})

// Association is defined in Message as follows
contacts: {
    collection: 'MessageContact',
    via: 'messageId',
    required: true,
    array: true,
}

Snippet above only validates Message and ignores MessageContact(s)

query-methods.md

Can we define the return type here for the methods beyond find and findOne on the docs?

I struggled alot with create vs update return values.

findOne: always {}
find: always [{}]
create: {} if {} passed [{}] if [{}] passed
update: always [{}]
destroy: always [{}]

I understand the theory for create, it returns based on the type you input, but update and destroy are always [{}] and this should be stated. Updating one record even by ID is returning me [{}]

Feature: Default Criteria

Is there a way to set default criteria on the model? I have a scenario where the legacy database has one table "instances" that have a type. The types can be A and B. Both A and B need to be treated as separate domain objects, and I would like to accomplish this by setting a default criteria on the models as such:

var A = Waterline.Collection.extend({
attributes: {
name: 'string',
....
},
defaultCriteria: {
type: 'A'
}
});

var B = Waterline.Collection.extend({
attributes: {
name: 'string',
....
},
defaultCriteria: {
type: 'B'
}
});

This would allow us to filter our query by type for all selects, without having to explicitly add the models default criteria on every query.

Get objects filtered by values depending on a relationships filter

Is it possible to make a query where I get records depending on the values of a relationships fields?

For example, this, which doesn't work:

{ 
    skip: 0,
    limit: 10,
    sort: 'id asc',
    where: { 
        or: [  
            { 'company.name': { contains: 'Admin' } },
            { name: { contains: 'Gru' } }
         ]
     }
}

What I would like to happen is to get all records where company.name contain 'Admin', that is the part I am not being able to do.

Is there a way to do this? Thanks

Clarification of accepted data types

While trying to create and/or update multiple records with one call, it was unclear if each of the accepted data types can be used together.
Example. When passing and array of object ids as the first parameter and a array of objects with new attribute data to update, what is the resulting action.

"Questions.update( toUpdateObjectIDs , newQuestionsAttribs )"

After test for a while, I could not get this to work. If this is supposed to work, ie can you give an array of objects for the first parameter and the second parameter.
Should this update each of first arrays objects with the corresponding arrays attributes?
Or does is try to update each of the first arrays objects with each (and every) of the attributes of the second array.

An example would also be incredibly helpful. Thanks.

Many-to-Many association. Failing on add() method.

var User = Waterline.Collection.extend({
    connection: 'mongodb',
    attributes: {
        firstName: {
            type: 'string'
        },
        ...
        username: {
            type: 'string',
            required: true,
            unique: true
        },
        ...
        // Add a reference to Questions
        starredQuestions: {   title: {
            type: "string",
            required: true,
            notEmpty: true
        },

} });

var Question = Waterline.Collection.extend({
    connection: 'mongodb',
    attributes: {
     ...
        starredBy: {
            collection: 'user',
            via: 'star'
        }
    } });

It fails when I tried to do this:

User.findOne(req.user.id).exec(function(err, user) {
                            if(err) { console.log(err); } // handle error

                            var star = Star.create({'username' : uname, 'question_id' : id, 'user_id' : req.user.id, 'unread' : true}, function (err, star) {
                                ...
                            });
user.starredQuestions.add(question.id);
user.save(function(err) {res.send({'message' : 'just starred it.'});
});

Error that I'm facing:

/home/rajan/sails/askable/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:245
        throw message;      
              ^
TypeError: Cannot call method 'add' of undefined
    at /home/rajan/sails/askable/api/controllers/QuestionController.js:338:51
    at bound (/home/rajan/sails/askable/node_modules/sails/node_modules/lodash/dist/lodash.js:957:21)
    at applyInOriginalCtx (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:416:80)
    at wrappedCallback (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:315:18)
    at _normalizeCallback.callback.success (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/normalize.js:33:31)
    at _switch (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/factory.js:35:28)
    at returnResults (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/lib/waterline/query/finders/basic.js:161:9)
    at /home/rajan/sails/askable/node_modules/sails/node_modules/waterline/lib/waterline/query/finders/basic.js:69:16
    at /home/rajan/sails/askable/node_modules/sails/node_modules/waterline/lib/waterline/query/finders/operations.js:82:7
    at Object.async.each (/home/rajan/sails/askable/node_modules/sails/node_modules/waterline/node_modules/async/lib/async.js:121:20)

Process finished with exit code 8

Where could it be failing? Thanks in advance.

many to many .populate error

I have one-to-many attribute and also a many-to-many attribute - when using .populate() I have resolved that an error is thrown when you attempt to .populate() the one-to-many association BEFORE the many-to-many association.

It seems to work if I .populate() many-to-many before .populate() one-to-many.

User.findOne("548e30d118cdb0c41553ccbd")
.populate('company')
.populate('regions')
.exec( function userFound(err, user) {
console.log('User Authenticated.');
console.dir(user);
});

----- throws err -------

/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:245
throw message;
^
TypeError: Cannot read property 'where' of undefined
at _afterFetchingJunctorRecords (/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/waterline-cursor/cursor/populateBuffers.js:131:35)
at /Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/lib/collection.js:103:5
at /Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/cursor.js:163:16
at commandHandler (/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/cursor.js:709:16)
at /Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/db.js:1846:9
at Server.Base._callHandler (/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
at /Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
at MongoReply.parseBody (/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
at null. (/Users/coryrobinson/projects/thermsv3/node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
at emit (events.js:95:17)
|mmBooyaH!| ~/projects/thermsv3

Using alternative name for foreign key

I am attempting to use populate for a one-to-one relationship however I've run in to a rather annoying issue. My problem seems like something rather trivial basically I have two tables that I want to join the name of the field is sadly the same in both tables refID so what I wanted to do was something like:-

refID: 'INTEGER',
properties: {
model:'SomeOtherModel',
via: 'refID'
}

This however returns a 500 error, I would think many legacy or even new DB designs would have unfortunate names for the foreign key ie. user_id, person_name etc. it seems to me it would be nice if you could give it a different name?

So while I'm aware the problem is bad database design, I'm stuck working with legacy MySQL tables which are updated via a C application that no one wants to touch. So I don't have a lot of choice. Any suggestions welcome.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.