Return object with updated association in Sequelize - mysql

Using Sequelize and MySQL, updating an object including the associated object it has. Everything updates fine but I can't get the new associated object to return. If I do another GET request it's the new one but I need it to come back on the response after an update.
I'm trying to just reload that contact object before return.
The object looks like this:
{
"id": 1,
"details": "some task details",
"contact": { //associated object
"associatedId": 1,
"name": "Mike",
}
}
This is what I'm trying
db.task.findOne({
where: {
id: taskId,
userId: req.user.get('id')
},
include: [db.contact]
}).then(
function(task) {
if (task) {
return task.update(attributes);
} else {
res.status(404).send();
}
},
function() {
res.status(500).send();
}
).then(
function(task) {
if(task) {
res.json(task);
}
},
function(e) {
res.status(400).json(e);
}
);

All you need to do is returning: true :
return task.update(attributes,{
returning: true,
plain: true
});

Related

How to ignore a variable in JSON data in Angular TypeScript

I am facing a problem while reading a JSON file in angular 7.
below is the format of my JSON data file.
[
{
"attributes": {
"User": "jay"
}
},
{
"attributes": {
"User": "roy"
}
},
{
"attributes":{
"User": "kiya"
}
},
{
"attributes":{
"User": "gini"
}
},
{
"attributes": {
"User": "rock"
}
},
{
"attributes": {
"User": "joy"
}
}
]
here is my component.ts file method in which I am calling service for a JSON file.
this.rest.getUsers().subscribe((data: {}) => {
console.log(data);
this.items = data;
//this.items=data;
});
Here is my service.ts file method.
private extractData(res: Response) {
let body = res;
return body || { };
}
getUsers():Observable<any> {
return this.httpService.get('./assets/usersdetails.json').pipe(
map(this.extractData));
}
Now I want to read only User from the JSON file and I want to filter the word attributes. is there any way to filter this thing from JSON file, so that I can only get the User value. because in my Project this attributes in JSON is creating a problem and I want to ignore or filter this.
because in my application I need to read the JSON as below format.
[
{
"User": "jay"
},
{
"User": "roy"
},
{
"User": "kiya"
},
{
"User": "gini"
},
{
"User": "rock"
},
{
"User": "joy"
}
]
but the data is coming in the format as above mentioned JSON format with attributes
so is there any way to filter the extra attributes thing from the JSON at the time of reading.
You don't show the code for the extractData method, so it is hard to say what isn't working there, but you should be able to accomplish your goals with the following.
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => d.attributes))
);
If there are other properties on 'attributes' and you really only want the 'user' data, then you could further update the code to:
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => ({ 'User': d.attributes.User })))
);

Stuck to figure out how to access a certain field to update

I have this JSON FILE
{
"_id": "GgCRguT8Ky8e4zxqF",
"services": {
"emails": [
{
"address": "Abunae#naa.com",
"verified": false,
"verifiedMail": "Toto#hotmail.com"
}
],
"profile": {
"name": "Janis"
},
"pushIds": []
}
I want to update my verifiedMail field but couldn't figure out how to do it in Meteor, it's always returning me an error
let VerifiedEmail = "Exemple1"
await Meteor.users.update({ _id: user._id }, { $set: { 'emails.verifiedEmail': emailRefactor} }, { upsert: true })
Couldn't figure out how to access the emails.verifiedEmail field
Tried this exemlpe worked like a charm
let VerifiedEmail = "Exemple1"
await Meteor.users.update({ _id: user._id }, { $set: { 'profile.name': emailRefactor} }, { upsert: true })
but couldn't figure out how to access emails.verifiedEmail .
Could you please help me ?
Emails is an array, while profile is an object. You have to access the first object of the email array instead
This updates the exact email address from emails
Meteor.users.update({
"emails.address": emailRefactor
}, {
$set: {
"emails.$.verified": true
}
});
Or update the first element
Meteor.users.update({
_id: user._id,
"emails.address": emailRefactor
}, {
$set: {
"emails.0.verified": true
}
});
You're trying to set verifiedEmail while the actual field is verifiedMail.

Sequelize orm using Association methods

Sequelize orm using Association methods
I'm working on a API using Node and Sequelize ORM. The database being used is MYSQL. I've used belongsTo() in below code.
Each user have favorite games. Get the favorite games for each user using user_Id.
I got a sequelize result and but excepting another.
this.userFavoriteGameModel = require("../entity/favorite_game")(this.database, this.Sequelize);
this.gameModel = require("../entity/game")(this.database, this.Sequelize);
//Fecth user favorite game list
favoriteGameList(name, cb) {
let self = this;
var user_Id = 5;
self.userFavoriteGameModel.belongsTo(self.gameModel, {
as: "game_detail",
foreignKey: 'game_Id'
});
self.userFavoriteGameModel.findAll({
attributes: [
'game_Id'
],
where: {
user_id: user_Id
},
include: [{
model: self.gameModel,
as: 'game_detail',
attributes: ["game_Title", "game_Subtitle", "icon", "game_Rating"]
}],
group: ['game_Id']
}).then(function (result) {
cb(result);
let obj1 = result;
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2));
}, function (err) {
console.log('An error occurred while creating the table:', err);
cb(err);
});
}
}
[
{
"dataObject": [
{
"game_Id": 57,
"game_detail": {
"game_Title": "battlefield1",
"game_Subtitle": "Limited edition",
"icon": "image.png",
"game_Rating": 2
}
},
{
"game_Id": 58,
"game_detail": {
"game_Title": "battlefield2",
"game_Subtitle": "Limited edition",
"icon": "image.png",
"game_Rating": 1
}
}
]
}
]
Excepting Result :
[
{
"dataObject": [
{
"game_Id": 57,
"game_Title": "battlefield1",
"game_Subtitle": "Limited edition",
"icon": "image.png",
"game_Rating": 2
},
{
"game_Id": 58,
"game_Title": "battlefield2",
"game_Subtitle": "Limited edition",
"icon": "image.png",
"game_Rating": 1
}
]
}
]
sequelize orm make nested json as result of hasMany belongsTo or other relations if you dont want it as final result you could get the sequelize result then make it manually like what you want follow this:
var finalResult={}
for(var key in object){
if(typeof object['key'] == 'object'){
var parent=object['key']
for(var childKey in parent){
finalresult['childKey']=parent['childKey']
}
}else{
finalresult['key']=object['key']
}
}

How can I pass the data from Django to a Shield UI Grid?

I'm new using Django and Shield UI, what I'm trying to do is trying to get data for a shieldGrid, making a request to get remote data from the server. I have the next code.
this is my .js
$("#id_table_diagnosticos").shieldGrid({
dataSource: {
remote: {
read: {
url: "/atender/ListadoDiagnosticos/",
dataType: "json",
operations: ["sort", "skip", "take"],
data: function (params) {
var odataParams = {};
if (params.sort && params.sort.length) {
odataParams["$orderby"] = window.orderFields[params.sort[0].path].path + (params.sort[0].desc ? " desc" : "");
}
if (params.skip != null) {
odataParams["skip"] = params.skip;
}
if (params.take != null) {
odataParams["top"] = params.take;
}
return odataParams;
}
}
},
schema: {
data: "fields",
total: function (result) {
return result["odata.count"];
},
fields: window.orderFields = {
// "pk": { path: "pk" },
"descripcion": { path: "descripcion" },
"codigo": { path: "codigo" },
}
}
},
paging: true,
sorting: true,
columns: [
// { field: "pk", title: "ID", width: 80 },
{ field: "descripcion", title: "Descripción", width: 180 },
{ field: "codigo", title: "Código", width: 100 },
]
});
});
my model.py is
class ParametrosDiagnosticos(models.Model):
descripcion=models.CharField(max_length=1000)
codigo=models.CharField(max_length=100)
sexo=models.CharField(max_length=10,default='Ambos')
estado=models.CharField(max_length=100, default='Activo')
estado_logico=models.IntegerField(default=1)
and my view.py
def ListadoDiagnosticos(request):
if request.user.is_authenticated:
if request.method=='GET' and request.is_ajax():
objeto=ParametrosDiagnosticos.objects.all()
data = serializers.serialize('json', objeto, fields=('pk','descripcion','codigo'))
return JsonResponse(data,safe=False);
The request to server is doing ok, the problem is that when I return the data, I get the next error on the console of my browser.
shieldui-all.min.js:4 Uncaught TypeError: Cannot read property 'map' of undefined
at e (shieldui-all.min.js:4)
at init.fields (shieldui-all.min.js:5)
at init.process (shieldui-all.min.js:5)
at init._success (shieldui-all.min.js:5)
at e (bundled.js:2)
at Object.z.func.i.success (shieldui-all.min.js:4)
at j (bundled.js:2)
at Object.fireWith [as resolveWith] (bundled.js:2)
at x (bundled.js:5)
at XMLHttpRequest.b (bundled.js:5)
Thank you for your help.
Make sure your Grid's dataSource.schema is configured correctly. Documentation about it can be found here.
For example, if your data returned from the server contains a list of objects, you do not need to set its data property.

Elasticsearch: how can i create mapping before upload json data into Elasticsearch

I'm trying to create mapping before uploading json data into elasticsearch.
I don't know how to implement mapping before uploading json data in sails.js
This is my bulkupload snippet
var body = [];
//row is json data
rows.forEach(function(row, id) {
body.push({ index: { _index: 'testindex', _type: 'testtype', _id: (id+1) } });
body.push(row);
})
client.bulk({
body: body
}, function (err, resp) {
if (err)
{
console.log(err);
return;
}
else
{
console.log("All Is Well");
}
});
I want to create mapping before data upload.can any one know how to create mapping in sails.
my Json object
[ { Name: 'paranthn', Age: '43', Address: 'trichy' },
{ Name: 'Arthick', Age: '23', Address: 'trichy' },
{ Name: 'vel', Age: '24', Address: 'trichy' } ]
Before making your client.bulk() call you first need to make another client.indices.putMapping() call like this in order to save the correct mapping for the data you're about to send via the bulk call:
client.indices.putMapping({
"index": "testindex",
"type": "testtype",
"body": {
"testtype": {
"properties": {
"your_int_field": {
"type": "integer"
},
"your_string_field": {
"type": "string"
},
"your_double_field": {
"type": "double"
},
// your other fields
}
}
}
}, function (err, response) {
// from this point on, if you don't get any error, you may call bulk.
});
Remember that all these calls are asynchronous, so be careful to only call bulk once putMapping has returned successfully.
Sounds like you need PutMapping.