I have the following two models: User and Job.
Each user can have just one job.
The user.attributes and job.attributes look like these (1):
(1)
user.attributes = {
id: 1,
name: 'barName',
job_id: 5
}
job.attributes = {
id: 5,
name: 'fooJob'
}
Let's suppose I want to make a relation between these two models:
The foreign key should be job_id
(2)
User = Backbone.ModelRelation.extend({
relations: [
{
type: Backbone.HasOne,
key: 'job_id',
keyDestination: 'job',
relatedModel: User
}
]
});
Using the code (2) the result will be:
(3)
user.attributes = {
id: 1,
name: 'barName',
job: job.attributes
}
As you can see the job_id from user.attributes is lost.
So, if I make a PUT request to the server, the server complains about the missing job_id attribute.
Any ideas how can I fix (3) in order to keep the job_id in user.attributes like (4)?
(4)
user.attributes = {
id: 1,
name: 'barName',
job_id: 5
job: job.attributes
}
Reference:
Paul Uithol - Backbone-relational
The workaround for me was to change the way the server reads the JSON posed.
So the server would read {user:{job:{id:1}}} rather than {user:{job_id:1}}
Note that we include a sub-object with an id attribute rather than use the job_id flat attribute.
Depending on which server side framework this can be configured.
Related
I am developing a CLI using Enquirer. I want user of the CLI to write javascript on a json.
So, i want something like this :
Create a Rule on the the data
const model = {
reviews: {
'5': [
{
customerId: 'A2OKPZ5S9F78PD',
rating: '5',
asin: 'asin2',
reviewStatus: 'APPROVED',
reviewId: 'R379DKACZQRXME',
},
],
'4': [
{
customerId: 'A2OKPZ5S9F78PD',
rating: '4',
asin: 'asin2',
reviewStatus: 'APPROVED',
reviewId: 'R379DKACZQRXME',
},
],
},
entityType: 'LIVE_EVENT',
entityId: 'event2',
};
Then user writes the rule.
Object.values(model.reviews).forEach(reviews =>
(reviews as any).forEach(review => {
if (parseInt(review.rating) < 3 && attributes.reviewId.Value.includes(review.reviewId)) {
output.push({
exceptionName: `Customer ${review.customerId} left a review ${review.reviewId} with rating ${review.rating}`,
});
}
})
);
While writing this rule, Since it is on the above json model, I want to provide autocomplete options on javascript and validate if it is correct javascript.
Is there a way to do this ?
If I'm understanding your question correctly, it sounds like you want to take the model object and write it to a JSON file.
If this is your goal, simply do the following:
import { writeFileSync } from "fs";
// Define the model
const model: any = { foo: bar };
// Transform the model object to JSON
const modelJSON: string = JSON.stringify(model, null, 4); // Indents the JSON 4-spaces
// Write the modelJSON to `model.json`
writeFileSync("./model.json", modelJSON);
The above is TypeScript, but the standard JavaScript version is basically the same. Make sure you add #types/node to your package.json file if you're using TypeScript - hope this helps!
My models:
Recipe (id, name)
Ingredient (id, name)
Recipe_Ingredient (recipeId, ingredientId, quantity)
My associations:
Recipe.belongsToMany(Ingredient, { through: Recipe_Ingredient })
Ingredient.belongsToMany(Recipe, { through: Recipe_Ingredient })
My problem:
How can I create a Recipe with some Ingredients and the quantities attached to them?
I tried:
Recipe.create({
name: 'Pizza',
ingredients:[
{
name: 'mozarella',
recipe_ingredients: {
quantity: 5
}
}
]
}, {
include:[Ingredient]
})
Records are created for Recipe, Ingredient and the Recipe_Ingredient. The only problem is that the value of the quantity is not collected from the data source.
It was not possible to do this in the past, but in October 23, 2018 this was fixed in sequelize PR #10050.
As of today (2018-10-24) the fix is not released yet, but as soon as v5.0.0-beta14 comes out, you'll be able to do the following:
Recipe.create({
name: 'Pizza',
ingredients: [
{
name: 'mozarella',
recipe_ingredient: {
quantity: 5
}
}
]
}, {
include: Ingredient
})
Also, note that the correct usage is recipe_ingredient: in the singular form, not in the plural form as you tried in your question. This makes sense, because for a given Ingredient, associated with a given Recipe, there is only one Recipe_Ingredient involved, always.
If you do not want to wait for v5.0.0-beta14 (although it will probably be released very soon), you can install it directly from github's master branch as follows:
npm install --save https://github.com/sequelize/sequelize/tarball/master
A solution I found, inspired by answers of pedro around here (How do I ORM additional columns on a join table in sequelize?) and there is given by a change of perspective.
receipe (name:string)
ingredient (quantity:int)
type (name: string)
receipe.hasMany(ingredient, {as:'ingredients'} )
ingredient.belongsTo(type)
and then I can consume data like this:
receipe.create({
name: 'Pizza',
ingredients:[
{
quantity: 5,
type: {
name: 'ingredient 1'
}
}, {
quantity: 6,
type: {
name: 'ingredient 2'
}
} {
quantity: 5,
type_id: 1
}]
}, {
include:[{
model; ingredient,
as: 'ingredients',
include:[{
model: type
}]
}]
})
It has some drawbacks but it is good enough for me.
One problem can be that if you add two items of the same new type, you will get a unique key violation (as types are unique and sequelize will not try to search if the type exists before trying to create it).
Another problem is that if you specify just the type_id in the data, it will not actually return the type refereed by that in the result.
var params = {
ImageId: 'ami-23ebb513',
InstanceType: 't1.micro',
MinCount:1, MaxCount: 1
};
ec2.runInstances(params, function(err, data) {
})
This code is good to start with launch instances. But i am trying to customize the instance's security group, public key for ssh etc. How can we configure these params?
I see not much docs is available that lists out the params supported by aws-sdk.
You should be able to get most of what you want with params.
Params additions would be:
NetworkInterfaces: [{DeviceIndex:0, SubnetId: 'subnet-12345', AssociatePublicIpAddress:true, Groups: ['sg-12345']}],
KeyName: 'MyKey'
The only thing you can't really get with the ec2-runInstances is tag creation. That would come from a second api call within the first function, like so:
params = {Resources: [data['instanceId']], Tags: [
{Key: 'Name', Value: 'SomeName-' + data['instanceId']},
{Key: 'Project', Value: 'My Project'},
{Key: 'SubProject', Value: 'SpotInstanceAuto'},
{Key: 'Creator', Value: 'Jason Nichols'},
...
]};
ec2.createTags(params, function(err) {
console.log("Tagging instance", err ? "failure" : "success");
...
});
I am currently using StrongLoop as my API backend server and Mongodb as data storage engine.
Let's say there is a collection called article. It has two fields title, and content. And there are two frontend pages to display a list of articles and view a single article.
Obviously the data list page only need title field and the view page need both. Currently the GET method of StrongLoop API return all fields including content. It cost extra traffic. Is there any way that can just return specific field?
Mongodb support projection in find() method for this. How can I do the same thing by StrongLoop?
Have you taken a look at the filters offered. http://docs.strongloop.com/display/LB/Querying+models
Query for NodeAPI:
server.models.Student.findOne({where: {RFID: id},fields: {id: true,schoolId: true,classId: true}}, function (err, data) {
if (err)
callback(err);
else {
callback();
}
})
Query for RestAPI :
$http.get('http://localhost:3000/api/services?filter[fields][id]=true&filter[fields][make]=true&filter[fields][model]=true')
.then(function (response) {
}, function (error) {
});
You can use fields projections,
Sample Record:
{ name: 'Something', title: 'mr', description: 'some desc', patient: { name: 'Asvf', age: 20, address: { street: 1 }}}
First Level Projection:
model.find({ fields: { name: 1, description: 1, title: 0 } })
and I think Strong loop is not yet supporting for second-level object filter, does anyone know how to filter second-level object properties or is yet to implement?.
Second Level Projection: (Need help here)
Ex: 2
model.find({ fields: { name: 1, 'patient.name': 1, 'patient.age': 1, 'patient.address': 0 } })
// Which results { name } only
I have tried several things to query both the team member name and capacity in Rally developer depending upon iteration. One of the challenges I run into is that the team member name and capacity are under two different types. So, matching the team member names with the capacity has been a challenge.
One of my failed attempts in accomplishing this is as follows:
var queryConfig = {
key: "teamMember",
type: "User",
fetch: "UserName,Role",
query: '(TeamMemberships != "")'
};
var queryByUserName = {
key: "teamDataByUser", type: "UserIterationCapacity",
fetch: "Capacity,ObjectID",
query: rally.sdk.util.Query.or(ownerQueries)
};
You should be able to get the user's capacity and that users name in one query using dependent field fetching.
var queryByUserName = {
key: "teamDataByUser", type: "UserIterationCapacity",
fetch: "Capacity,ObjectID,User,DisplayName",
query: rally.sdk.util.Query.or(ownerQueries)
};
This query will return data that looks like:
{
ObjectID: 64265714,
Capacity: 6,
User: {
_ref: "https://rally1.rallydev.com/slm/webservice/x/user/1234.js",
ObjectID: 1234,
DisplayName: "Cindy"
},
_type: "UserIterationCapacity"
}