Update Sequelize Array - arrays

I have looked everywhere, and I have not found an easy to understand method of updating a sequelize array, like this with a normal string:
db.User.update({name:req.body.name},{where : {username:req.body.username}}).then(function(user) {
res.json(user);
})

Sequelize doesn't support bulk updates using an array, see https://github.com/sequelize/sequelize/issues/4501
You have to implement a custom function.
Here is a basic example to give you an idea :
var promises = [];
userArray.forEach(function(user){
promises.push(db.User.update({name:user.name},{where : {username:user.username}});
});
Promise.all(promises).then(function(){
// success
}, function(err){
// error
});

Which I myself resolved as follows:
case 1: If you want to update multiple lines at the same value with different conditions
db.User.update({ name: 'name request' }, {
where: {
$or: [{ name: 'test 1', password: 'sasaccsa' }, {
name: "test 2"
}]
}
}).then(function(user) {
//query generate
// UPDATE `User` SET `name`='name request' WHERE ((`name` = 'test 1' AND `password` = 'sasaccsa') OR `name` = 'test 2')
res.json(user);
});
case 2: if you want to update multiple lines with different values for different types of reviews:
var arrayUpdate = [{
name: 'test 1',
id: 1
}, {
name: 'test 2',
id: 2
}, {
name: 'test 3',
id: 3
}];
sequelize.Promise.each(arrayUpdate, function(val, index) {
return db.User.update({
name: val.name
},{
where:{
id: val.id
}
}).then(function(user) {
}, function(err){
});
})
.then(function(updateAll){
//done update all
res.json(updateAll);
}, function(err){
});

Related

Mongodb project only keys in an object

I am trying to return only the values in an array. I managed to solve this a few months ago on a different project but I have forgotten how.
Here is my current query and the result.
database.find({todo: {$exists: true}},{projection:{_id: 0}}).toArray((error,data) => {
console.log(data);
res.json(data);
});
[
{
todo: {
id: '30a508fbfb8a51d2784920c2d6b7468c',
text: 'testing',
completed: false
}
},
{
todo: {
id: 'dedf6f6a850f7fef02566de027e74416',
text: 'testing',
completed: false
}
}
]
I would like it to return only the values in the Todo array as seen below. What do I need to add in the projection field to make this happen?
[
{
id: '30a508fbfb8a51d2784920c2d6b7468c',
text: 'testing',
completed: false
},
{
id: 'dedf6f6a850f7fef02566de027e74416',
text: 'testing',
completed: false
}
]
Thank you,
I was able to figure it out. Turns out I was using the wrong function.
If there is anyone looking for this solution you want to use distinct and not projections.
database.distinct('todo', function(err, data) {
console.log(data);
});
This resulted in the following below which is what I was needing.
[
{
id: '30a508fbfb8a51d2784920c2d6b7468c',
text: 'testing',
completed: false
},
{
id: 'dedf6f6a850f7fef02566de027e74416',
text: 'testing',
completed: false
}
]
Thanks,

How to construct multiple dictionaries to array in react native

I am trying to show Expand/Collapse Flatlist data in react-native.
It is like single parent with multiple childs. So, If user tap on the cell, I have to show multiple rows for that expand/collapse.
But, I am getting data from server like following.
[{
code: '1212',
name: 'Bajaj Model 1',
url: 'Some url',
category: 'Bike'
},
{
code: '1213',
name: 'Bajaj Model 2',
url: 'other url',
category: 'Bike'
},
{
code: '1454',
name: 'BMW Model 1',
url: 'Some url',
category: 'Car'
},
{
code: '1454',
name: 'BMW Model 2',
url: 'Some url',
category: 'Car'
}
]
So, All the Bike data, I have to show one place like Parent and child.
For that I have done filter.
const fundsFilterData = mapValues(groupBy(response, 'category'),
fundslist => fundslist.map(item => omit(item, 'category')));
And I am getting like following.
{
'Bike': [{
code: '1212',
name: 'Bajaj Model 1',
url: 'Some url'
},
{
code: '1213',
name: 'Bajaj Model 2',
url: 'other url'
},
],
'Car': [{
code: '1454',
name: 'BMW Model 1',
url: 'Some url'
},
{
code: '1454',
name: 'BMW Model 2',
url: 'other url'
},
]
}
But, I want to make it as array along with some pre added keys like following.
[{
'Title': 'Bike',
'Values': [{
'code': '1212',
'name': 'Bajaj Model 1',
'url': 'Some url'
},
{
'code': '1454',
'name': 'Bajaj Model 2',
'url': 'other url'
}
]
},
{
'Title': 'Car',
'Values': [{
'code": '
1454 ',
'name": '
BMW Model 1 ',
'url": '
Some url '
},
{
'code': '1454',
'name': 'BMW Model 2',
'url': 'Some url'
}
]
}
}
So that I can show Titles in headers and once user tap on row, I can show child's data as expanded.
Any suggestions?
Use _.map() which returns an array, and not _.mapValues(). In the _.map() get the Title (the key) from the 2nd param. Use it and the values (after _.omit()) to construct an object for each group.
const { map, groupBy, omit } = _;
const response = [{"code":"1212","name":"Bajaj Model 1","url":"Some url","category":"Bike"},{"code":"1213","name":"Bajaj Model 2","url":"other url","category":"Bike"},{"code":"1454","name":"BMW Model 1","url":"Some url","category":"Car"},{"code":"1454","name":"BMW Model 2","url":"Some url","category":"Car"}];
const fundsFilterData = map(
groupBy(response, 'category'),
(list, Title) => ({
Title,
Values: list.map(item => omit(item, 'category'))
})
);
console.log(fundsFilterData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Cannot read property 'map' of undefined in sequelize nodejs

This is my api:
exports.getService = function(req, res) {
var limit = 10; // number of records per page
var offset = 0;
Service.findAndCountAll({
raw: true,
where: {
shop: req.user.shop
}
}).then((data) => {
var page = req.params.page; // page number
var pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
Service.findAll({
// raw: true,
limit: limit,
offset: offset,
$sort: {
id: 1
},
where: {
shop: req.user.shop
},
include: [{
model: Categoryservice,
attributes: ['id'],
include: [{
model: Category,
attributes: ['id', 'name'],
}]
}],
}).then(function (services) {
var services=JSON.parse(JSON. stringify(services));
console.log('=====stringify==========>>',services);
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
}).catch(function(error) {
res.status(500).send('Internal Server Error');
});
};
I am using map in last then fuction ,
It contains a error map undefined in the server..
I want want a out like below given json using the map fuction.
Actually i need this out put:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [
1,
2
]
}
my JSON. stringify(services) out put is:
=====stringify==========>> [ { id: 2,
username: null,
name: null,
image: null,
service: 'mobile',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '20',
per: '10',
tax: '1',
activity: null,
createdAt: '2018-03-14T07:30:57.000Z',
updatedAt: '2018-03-14T07:30:57.000Z',
categoryservices: [ [Object], [Object] ] },
{ id: 1,
username: 'sam',
name: 'New Service',
image: '/images/uploads/22-Feb-2018/f96334384cd78754454c5e4e05e20fc0-dragon_pattern_red_black_9666_1920x1080.jpg',
service: 'battery',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '5',
per: '1',
tax: '1',
activity: '2018-03-14T06:01:36.000Z',
createdAt: '2018-03-14T06:01:36.000Z',
updatedAt: '2018-03-14T06:01:36.000Z',
categoryservices: [] } ]
I was beginner of using map function,
so,I am confused in map ,
so please give any solution to this problem.
You are stringifying your array that comes back. You can't do that if you plan to use .map on it. Remove that code and try again.
.then(function (services) {
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
I think we are missing something because the output you pasted doesn't have the category.id attribute that you are returning from the item passed in to map. Is that what you are trying to target? That's off topic, but this code may not work for what you are trying to achieve but will run the map though.
Looks like services is an array, based on the console.log. If you want the id's of all categories, you can do
let categoryIds = [];
categoryIds = services.reduce((categoryIds, service) => {
let ids = service.categoryservices.map(category => category.id);
for(let id of ids) {
if(categoryIds.indexOf(id) === -1) {
categoryIds.push(id)
}
}
return categoryIds;
}, categoryIds);
If you want to have category ids as cats in each service, you can do,
var services=JSON.parse(JSON. stringify(services));
services.forEach(service) => {
service.cats = service.categoryservices.map(category => category.id);
delete service.categoryservices;
});
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
Hope this helps!

get and getList why no have the same unit?

In my application I'm having the bellow problem
SERVER RESPONSE DATA
route /users
{ data: [
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
] }
route /users/5
{ data: { id: 5, name: 'peter' } }
case01
Restangular.one('users', 5).get().then(function(user){
$scope.user = user;
});
case02
Restangular.all('users').getList().then(function(users){
$scope.user = users[0];
});
In my case02 I can access $scope.user.id, but in case01 I have that to do $scope.user.data.id (what's not preferible when I render this in my template with {{ user.id }} where I have that use {{ user.data.id }} )
In my case02 I can change my data and use $scope.user.save(), but in my case01 I can't access this function
In my restangular I configure this for handle data from server when I use getList because it come in one object and not in one Array
RestangularProvider.setResponseInterceptor(function(response, operation, what) {
if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
});
So I would not work, because then I will have a normal JS object and not a Restangular object, the Restangular object has several methods that I still intend to use the same $scope, so we would like to preserve this.
example:
In an item from a case02 consultation (array) I have an object with methods of Restangular:
all (), allUrl (), one (), oneUrl (), ... and the properties of the object I sought (id, name) within $ scope.user.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
id: data_from_user,
name: data_from_user
}
In an item from a case01 query (object) I have an object with methods of Restangular within $ scope.user and object properties that sought (id, name) within $ scope.user.data.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
data: {
id: data_from_user,
name: data_from_user
}
}
For this reason it would not work the solution you presented because it is okay to work with restangular the subject, not an object of normal JS, but thank you for the answer Tim Castelijns.
if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
If operation is getList, you return response.data, which is
[
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
]
but if operation is not getList, you return response, which is the entire object, including the data sub-object
{
data: {
id: 5,
name: 'peter'
}
}
Your choice to return different results depending on what operation it is, is the reason you need to do user.data.id for case01, because you assign the result to user with then(function(user), when in fact user represents the entire data sub-object containing the user.
You should be able to solve it by changing to this
Restangular.one('users', 5).get().then(function(response){
$scope.user = response['data'];
});

UI Bootstrap Typeahead is not displaying the values returned async

I am trying to do an autocomplete search using UI Bootstrap Typeahead to select a data from a database.
My service returns data in my response, but data are not listed in the component.
When I put a breakpoint in the component code , the list is there and when I continue to debug the list is displayed, but if it runs without breakpoints , the list is not displayed.
HTML
<input id="inputInstalation"
ng-model="profile.instalation"
typeahead-editable="false"
typeahead="installation as installation.name for installation in searchInstallation($viewValue)"
typeahead-input-formatter="formatLabel($model)"
ng-required="true">
Controller
$scope.searchInstallation = function(text){
return $http.get('/api/installations/name/' + text).then(function(response){
return response.data;
});
};
$scope.formatLabel = function(model){
return model ? model.name : "";
};
API NodeJS - DB Mongo
exports.findByName = function(req, res){
var connection = getConnection();
var Installation = getInstallationModel(connection);
Installation.find({name: new RegExp(req.params.name, "i")}, function (err, result) {
connection.close();
if(err) throw err;
res.json(result);
});
};
Response
[{ _id: 5525662b74100eb40f13ce00,
name: 'test 2',
description: 'Gdoc 02.02.00-00',
__v: 0,
services:
[ { name: 'Alfresco',
context: '/alfresco',
parameterURL: 'prmGdocServiceUrl',
_id: 5525662b74100eb40f13ce03 },
{ name: 'ri-rest',
context: '/iserver',
parameterURL: 'prmUrlIntegrationServer',
_id: 5525662b74100eb40f13ce02 },
{ name: 'ldap',
parameterURL: 'prmLdapUrl',
parameterUser: 'prmLdapPrincipal',
parameterPassword: 'prmLdapPassword',
_id: 5525662b74100eb40f13ce01 } ],
tables:
[ { _id: 5525662b74100eb40f13ce06, name: 'esegsistema' },
{ _id: 5525662b74100eb40f13ce05, name: 'esegusuario' },
{ _id: 5525662b74100eb40f13ce04, name: 'XPTO' } ],
parameters:
[ { name: 'prmUrlBaseServidorHTTP',
systemCode: '314',
_id: 5525662b74100eb40f13ce0e },
{ name: 'prmTamanhoMaximoArquivo',
systemCode: '314',
_id: 5525662b74100eb40f13ce0d },
{ name: 'prmGdocServiceUrl',
systemCode: '314',
_id: 5525662b74100eb40f13ce0c },
{ name: 'prmLdapUrl',
systemCode: '314',
_id: 5525662b74100eb40f13ce0b },
{ name: 'prmLdapPrincipal',
systemCode: '314',
_id: 5525662b74100eb40f13ce0a },
{ name: 'prmLdapPassword',
systemCode: '314',
_id: 5525662b74100eb40f13ce09 },
{ name: 'prmDomainSufix',
systemCode: '314',
_id: 5525662b74100eb40f13ce08 },
{ name: 'xxxxx',
systemCode: '314',
_id: 5525662b74100eb40f13ce07 } ] }]
I found the problem, I'm using the https://github.com/McNull/angular-block-ui and it conflicts with the component.
Solution : I created a requestFilter from angular blockui to don't block requests sent the component to API .

Resources