How I can change name in request object, if I use sequelize.
I have two models, and Person model include Name model.
Table in db is Names, and my field name is Names.
How I can . change it?
Person.findByPk(
id,
include: [{
model: Name
}]
});
Name.Model.js
sequelize.define('Name', {
id: {
type: type.INTEGER,
primaryKey: true
},
name: {
type: type.STRING
}
});
and I get object Person, where one filed is also object
Person = {
...
Names: {
id: 1,
name: Piter
}
}
I want
Person = {
...
name: {
id: 1,
name: Piter
}
}
You should be able to use the as property in your association wherever you defined it. For example your Person Model could look like this.
const Person = sequelize.define('Person',
{
.
. //whatever other properties your person has.
.
},{});
Person.associate = function(models){
Person.hasOne(models.Name, {
as: 'name'
});
};
Edit: More information regarding this subject can be found here: http://docs.sequelizejs.com/manual/associations.html#naming-strategy
Related
Given an object like this:
var fullObj = {
prop1: "myProp1",
subobject: {
Obj1_id: {
id: "Obj3_id",
name: "./",
otherProperties:...
},
Obj2_id: {
id: "Obj2_id",
name: "Obj2_id",
...
},
Obj3_id: {
id: "Obj3_id",
name: "Obj3",
....
},
I would like to trim the name if it is too long(more than myLength) plus 3 dots
I know like to use something like that otherwise just the name
name=name.substr(0,myLength)+"..."
Given that this object is in a react state how can I manipulate the state (using class based component)?
I hope this is what you were looking for. It will check if the value of name is greater then 3 then it will take the first 3 letters from the name and add ... in it.
Object.keys(fullObj.subobject).forEach(function(key) {
if(fullObj.subobject[key].name.length > 3){
fullObj.subobject[key].name = fullObj.subobject[key].name.slice(0,3) + "..."
}
});
I am trying to build my listings model in a way where it restricts users to only select a subcategory if it exists in the parent array list. I can do this when I am building the API end point fine but I wanted to see if its possible to do this within the Model itself.
here is an example:
If(a user selects parent category household from the parent enum category array)
.then(set ENUM array based of the parent category)
Code Reference:
Model:
var categories = require(settings.PROJECT_DIR + 'controllers/data/categories');
var ListingSchema = mongoose.Schema({
data: {
category: {
parent: {
type: String,
enum: categories.parent(),
required: true
},
sub: {
type: String,
enum: categories.sub("household"), // should be this.data.category.parent instead of hard coded value
required: true
}
},
}
}
The Categories Array:
module.exports.categories = [
{ "household" : ["repair", "carpentry", "housecleaning", "electrical", "handymen", "movers", "plumbing", "gardening/pool"] },
{ "automotive" : ["autobody", "mechanics", "towing"] },
{ "creative" : ["art", "cooking", "film", "graphic_design", "marketing", "music", "writing"] },
{ "tech" : ["tech", "repair", "web_design", "web_development"] },
{ "events" : ["artist", "florist", "musician", "photography", "planning", "venue"] },
{ "legal" : ["accounting", "advising", "investments", "consulting", "real_estate"] },
{ "health" : ["beauty", "fitness", "nutrition", "therapeutic"] },
{ "pets" : ["grooming", "sitter", "trainer", "walker"] }
];
// #returns parent categories
module.exports.parent = function() {
var self = this;
var parentCategories = [];
for(var i in self.categories) {
parentCategories.push( Object.keys(self.categories[i])[0] );
}
return parentCategories;
}
// #returns sub categories based of parent input
module.exports.sub = function(parent) {
var self = this;
var subCategories = [];
for(var i in self.categories) {
if(self.categories[i][parent]) {
return self.categories[i][parent];
}
}
}
It is not possible in the model.
mongoose.Schema() methods creates a Schema object based on the parameter supplied to it. And the created object is stored in ListingSchema. Since the object is created the first time mongoose.Schema() method gets executed, you cannot modify the values dynamically after that. Which means the value accepted by enum cannot be changed once it's set.
The best approach is to add all the values in a single array then set it as the value of enum and do the sub category restriction somewhere else.
How can I use normalizr to deal with nested standardised JSON API responses that are key via the { data: ... } standard?
For example a Book
{
data: {
title: 'Lord of the Rings',
pages: 9250,
publisher: {
data: {
name: 'HarperCollins LLC',
address: 'Big building next to the river',
city: 'Amsterdam'
},
},
author: {
data: {
name: 'J.R.R Tolkien',
country: 'UK',
age: 124,
}
}
}
}
How would I design schemas to deal with the nested data key?
For each entity in your response, you should create it's own schema.In your example, we have three entities - books, authors and publishers:
// schemas.js
import { Schema } from 'normalizr';
const bookSchema = new Schema('book');
const publisherSchema = new Schema('publisher');
const authorSchema = new Schema('author');
If some entity contains nested data which should be normalized, we need to use define method of it schema.This method accepts an object with nesting rules.If we need to normalize publisher and author props of book entity, we should pass an object to define function with same structure as our response:
// schemas.js
bookSchema.define({
data: {
publisher: publisherSchema,
author: authorSchema
}
});
Now we can normalize our response:
import { normalize } from 'normalizr';
import { bookSchema } from './schemas.js';
const response = {
data: {
title: 'Lord of the Rings',
pages: 9250,
publisher: {
data: {
name: 'HarperCollins LLC',
address: 'Big building next to the river',
city: 'Amsterdam'
},
},
author: {
data: {
name: 'J.R.R Tolkien',
country: 'UK',
age: 124,
}
}
}
}
const data = normalize(response, bookSchema);
I believe what you're after is the use of the assignEntity function which can be passed in the options of normalize. In this instance it lets us, where appropriate, filter out the redundant data properties and go straight to the values underneath.
Effectively assignEntity let's you control how each key of data is normalized. Take a look here for a little more on how it works.
I put this together as a demonstration, take a look: http://requirebin.com/?gist=b7d89679202a202d72c7eee24f5408b6. Here's a snippet:
book.define({
data: {
publisher: publisher,
author: author,
characters: normalizr.arrayOf(character)
}}
);
publisher.define({
data: {
country: country
}
});
const result = normalizr.normalize(response, book, { assignEntity: function (output, key, value, input) {
if (key === 'data') {
Object.keys(value).forEach(function(d){
output[d] = value[d];
})
} else {
output[key] = value;
}
}});
Also see in particular Ln 29, where the array of characters has some objects with the information nested within data and some without. All are normalized correctly.
I also added some parts to show how it works with arrays and deeply nested data, see the country model within publisher.
With the data provided you will need a slug due to the absence of id's, which each schema also contains in the example.
Normalizr is fantastic, I hope that helps explain a little more about it :)
I've been looking at sailsjs lately and by looking at the documenation http://sailsjs.org/#/documentation/concepts/ORM/Models.html
especailly this:
// From api/models/Person.js...
module.exports = {
attributes: {
// Primitive attributes
firstName: {
type: 'string',
defaultsTo: ''
},
lastName: {
type: 'string',
defaultsTo: ''
},
// Associations (aka relational attributes)
spouse: { model: 'Person' },
pets: { collection: 'Pet' },
// Attribute methods
getFullName: function (){
return this.firstName + ' ' + this.lastName;
},
isMarried: function () {
return !!this.spouse;
},
isEligibleForSocialSecurity: function (){
return this.age >= 65;
},
encryptPassword: function () {
}
}
};
It seems like heavy sql minded, how can I have attributes that are array of objects? like mongodb.
For example maybe my Person model has an attribute called liked_movies which is an array of movies that each movie has its own name and length
You should use model associations.
Salis docs about associations
In the example of the movies you are asking, a many to many association will do. Sails will create the pivot table for you. It will also create a REST like url for that association. i.e person/:personId/likedMovies
I want to know if there is a way to extract / search the elements which contain similar property from a javascript object.
Just to be more specific, If I have the following object:
Live Demo: http://jsfiddle.net/oscarj24/sMWUL/
var enrolled = {};
enrolled['enrolled/ruby/S1234'] = {
course: {
id: 'P01',
desc: 'Ruby course'
},
student: {
id: 'S1234',
name: 'John Doe'
}
};
enrolled['enrolled/php/S1234'] = {
course: {
id: 'P02',
desc: 'PHP course'
},
student: {
id: 'S1234',
name: 'Foo Bar'
}
};
enrolled['enrolled/java/S6666'] = {
course: {
id: 'P03',
desc: 'Java course'
},
student: {
id: 'S6666',
name: 'Bill Gates'
}
};
Then I'll have some similar properties inside the enrolled object (like the ones sharing the S1234 string at the end).
So, my question is:
How can I extract the elements with string similarities or coincidences in the properties?
I've looked that javascript objects are very limited and the only thing I can do to check if a property exists or not is: obj.hasOwnProperty(prop) (but this is not what I am looking for). Is there a way to use regex to check for this? (just saying, seems not to be possible).
Just to know, I am using ExtJS 4.2 but I can't find something to achieve what I need in the API documentation (correct me if wrong).
You can use a for each loop to see if what you're searching for is in the string.`
for (key in enrolled)
{
if(key.indexOf('S1234') > -1)
{
console.log(key);
//Perform your actions here
}
}
Fiddle here: http://jsfiddle.net/brettwlutz/sMWUL/2/
how about this?
for(var prop in enrolled){
console.log(prop);
//check if prop matches string regex.
}