I'm really stuck with this code and can't find the solution. I have created an Ionic app with connection to Firebase and my auth is working fine; can pass the data, but I can't see how should I pass the following code correctly. Form Structure:
My code for passing data, the Service:
factory('Products', function($firebaseArray) {
var productsRef = new Firebase("https://kidsmoments-19623.firebaseio.com/momentos");
var products =$firebaseArray(productsRef.child('products'));
var Products = {
saveProduct: function (product, image) {
var newProduct = {
name: product.name
, tagline: product.tagline
, description: product.description
, price: product.price
, image: image
};
return products.add(newProduct).then(function () { console.log('added');
})
}
};
return Products;
}
)
It looks like you forgot to add 'Products' as a dependency in the controller you were working on.
Also you should try Firebase three-way-binding:
.factory("Products", ["$firebaseObject", "$rootScope",
function($firebaseObject, $rootScope) {
return function() {
// create a reference to the database where our Products is.
var ref = ($rootScope.ref.child("Products"))
return $firebaseObject(reg);
}
}
])
And from the controller:
Products().$bindTo($scope, "products");
Now any change that you do to $scope.products will be synced to Firebase
I believe you have an entity products, so make a reference to that entity and push your data like this:
var productsRef = new Firebase("https://kidsmoments-19623.firebaseio.com/momentos/products");
productsRef.push({
name: product.name,
tagline: product.tagline,
description: product.description,
price: product.price,
image: image
})
Update About the error that you get please make sure you have injected the provider to your settings controller
Related
Currently, I'm trying to create a Discord bot that will save a to-do list in a database. To do so, I wanted to use an array that contains any items the person adds by typing !listadd (something) that will then be stored in a MongoDB database. However, while this seems to work for Strings, I cannot seem to change an array at all using this method.
await list.findOneAndUpdate({_id: id},{$push:{todoList: msg}, itemToAdd:msg},{upsert : true})
This line above is what I'm using to update the list. While the change to itemToAdd is reflected perfectly in the database, nothing is pushed to todoList. I can't even seem to update todoList at all past setting what the default value is in the schema. (Like, if I put {todoList:['one','two']} as the update object, it still won't do anything)
I've tried using the .updateOne() method and, again, it works fine for itemToAdd, but nothing happens to todoList. I've also tried using the .markModified() method and I've either used it wrong or it isn't working here because, still, nothing changes in the database.
Full Code:
const mongoose = require('mongoose');
const todoSchema = new mongoose.Schema({
todolist : [String],
_id: {
type : String,
required : true
},
itemToAdd:{
type: String,
required: false
},
indexOfItemToRemove:{
type: Number,
required: false
}
});
const list = mongoose.model('list', todoSchema);
module.exports = async (client) => {
client.on('message', async (message) => {
const { author } = message;
const { id } = author;
const { bot } = author;
if (!bot){
console.log('AUTHOR:', author);
if (message.content.includes('!listadd ')){
const msg = message.content.substring(9)
await list.findOneAndUpdate({_id: id},{$push:{todoList: msg}, itemToAdd:msg},{upsert : true})
message.reply('Entry Added!')
}
if (message.content.includes('!listget')){
let doc = await list.findOne({_id:id})
message.reply(doc.itemToAdd)
}
}
})
}
I am building a flutter application and using amplify_flutter 0.2.1 and amplify v5.1.0
, when I pull the project from the Amplify-admin UI it generates a graphQL schema schema.graphql which is useless at front-end because in order to fetch or modify the document, every time we need to write the graphQL query document like this:
String graphQLDocument =
'''mutation CreateTodo(\$name: String!, \$description: String) {
createTodo(input: {name: \$name, description: \$description}) {
id
name
description
}
}''';
var operation = Amplify.API.mutate(
request: GraphQLRequest<String>(document: graphQLDocument, variables: {
'name': 'my first todo',
'description': 'todo description',
}));
Amplify Flutter official CRUD Doc
I want to write it like this:
const input = {
name,
description
};
const output = {
id,name,description
};
var graphQLDoc = createToDO(input,output); // it should return the string object according to the input and output passed.
var operation = Amplify.API.mutate(
request: GraphQLRequest<String>(document: graphQLDoc, variables: {
'name': 'my first todo',
'description': 'todo description',
}));
OR it can be advanced like this:
const input = {
name:"hackrx",
description: "this works cool"
};
const output = {
id,name,description
};
var graphQLQueryRes = await createToDO(input,output); // it should return the whole fetched object according to the output passed.
you can do this way that I use in my code:
String myMutation(name, description) {
var graphQLDocument = '''mutation CreateTodo {
createTodo(input: {name: $name, description: $description}) {
id
name
description
}
}
''';
return graphQLDocument;
}
var operation = Amplify.API.mutate(
request:
GraphQLRequest<String>(document: myMutation('john', 'doe')));
for getting the response:
you can run amplify codegen models in the terminal that generate data models, based on your schema.graphql tables. and after that, you can do it this way: e.g you have a user table
User.fromJson(operation.response.data['createToDo]);
now you have an object of user class.
I'm using sails.js for a project and everything is going fine so far. Except that I don't know how to have an optional association between my two models. If I don't specify one, then if I use populate() it takes the first one available.
I have those two models:
// Book.js
module.exports = {
attributes: {
title: 'string',
serie: { model: 'serie' }
},
};
// Serie.js
module.exports = {
attributes: {
name: 'string',
books: { collection: 'book', via: 'serie' }
}
};
If I do this:
$ sails console
> Book.create({title: "Title"}).exec(function(err, book) {
Book.findOne({id: book.id }).populateAll().exec(function(err, book) {
console.log(book);
});
});
I get this:
{
serie: { name: 'Previously inserted serie' },
title: 'Title',
id: '55d6230122e3b1e70d877351'
}
Why isn't serie empty ? When inserting the book, I didn't specify any serie but it is still linked to a random one.
It was actually a bug from the sails-mongo adapter. I made a pull request that fixes it.
I am trying to give a default association from a user to a pet, whenever a new User created.
Model:: User.js
var User = {
attributes: {
name: {type: 'string'},
// Add a One Way Relation to pet model
pets: {
collection: 'pet'
},
},
/*** This did not work ***/
beforeCreate: function (user, next) {
var defaultPet = {name: 'Default Pet 1'};
Pet.find(defaultPet).exec(function(err, pet) {
user.name = "BEFORECREATE",
user.pets = pet[0].id;
next();
});
},
}
module.exports = User;
However when a new record is created the user.pet is [ ], but user.name is changed to "BEFORECREATE".
How do I get user.pets = [{name: 'Default Pet 1'}] automatically for the new user created?
Or is there a better place for setting such defaults?
----- UPDATE: More info
I am using sails-disk currently.
Model: Pet.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true
}
}
};
You can't add associations to a model in a lifecycle callback like beforeCreate. Currently, Waterline looks for and processes "nested models" like these before lifecycle callbacks run, so by the time beforeCreate is called it's too late. The simplest solution would be to create a User.createUser class method that wraps the logic you want:
createUser: function(data, cb) {
// If there are already pets specified, just use those
if (data.pets) {return User.create(data).exec(cb);}
// Otherwise look up the default pet
Pet.findOne({name:"Default Pet 1"}).exec(function(err,pet) {
// Return in case of error
if (err) {return cb(err);}
// Assuming the default pet exists, attach it
if (pet) {
console.log("SETTING DEFAULT PET", pet.id);
data.pets = [pet.id];
}
// Create the pet
return User.create(data).exec(cb);
});
}
A few notes:
In your example you were setting pets directly to an ID, but since it's a collection you must set it to an array.
If you're using the sails-disk adapter, you'll need to set schema: true in your model for this to work.
The new User model you get back will not be populated; you'll have to do a find with a populate('pets') with the new User ID to get the pet data attached.
I have a grid, which has a payments store. The Payment model, which it's store uses, has a field which is a date.
I've already implemented grouping by date, but that gives me a group of entries for each day, like this...
What I want to do is have a group for each month instead of each day.
Any ideas on how to do this?
Ok, nevermind. I just found a way to do this. I created a field using convert to find the month of the payment and used that field as the grouping field.
I'll leave this posted in case anyone ever needs it.
This is the Payment model...
Ext.define('Ext.model.Payment',{
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
fields: [
{
name: 'n_id_payment',
type:'integer'
},{
name: 'n_amount',
type:'integer'
}.....,
..... Several other fields .....
},{
name:'payment_month',
type:'date',
convert:function(model, record){
var today = new Date(record.data.dt_date);
var dd = today.getDate();
var mm = today.getMonth();
var month=new Array();
month[0]="Enero";
month[1]="Febrero";
month[2]="Marzo";
month[3]="Abril";
month[4]="Mayo";
month[5]="Junio";
month[6]="Julio";
month[7]="Agosto";
month[8]="Septiembre";
month[9]="Octubre";
month[10]="Noviembre";
month[11]="Diciembre";
return month[mm];
}
}
]
})
And this is the payment store...
Ext.define('Ext.store.PaymentsStore', {
extend: 'Ext.data.Store',
requires: [
'Ext.model.Payment',
'Ext.data.proxy.Memory'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
async:false,
groupField:'payment_month',
model: 'Ext.model.Payment',
method:'POST',
proxy: {
isSynchronous:true,
type: 'ajax',
url: 'http://localhost/index.php/TblPayment/fetch',
reader:{
type :'json',
method:'POST'
}
}
}, cfg)]);
}
});
This is the groupingFeature config...
var groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
groupHeaderTpl:'{name}'
});
The grid should have this property set too features: [groupingFeature]
And in case you're stuck with an error with grouping, something about getRowStyleTableEl being null... There's a workaround for that issue...
Ext.override(Ext.view.Table, {
/*
Temporary fix for bug in ExtJS 4.2.1. See: sencha.com/forum/showthread.php?264657-Exception-When-Selecting-First-Grid-Row
*/
getRowStyleTableElOriginal: Ext.view.Table.prototype.getRowStyleTableEl,
getRowStyleTableEl: function() {
var el = this.getRowStyleTableElOriginal.apply(this, arguments);
if (!el) {
el = {
addCls: Ext.emptyFn,
removeCls: Ext.emptyFn,
tagName: {}
}
}
return el;
}
});