Group By in lodash with a condition - node.js

[ { id: 4,
category_id: 7,
user_id: 2,
title: '',
image1: '15717679702861gohz24vrk2262fov.jpg',
image2: '15717679702891gohz24vrk2262fox.jpg',
image3: '15717679702911gohz24vrk2262foz.jpg',
image4: '15717679702921gohz24vrk2262fp0.jpg',
image5: '15717679702931gohz24vrk2262fp1.jpg',
status: 2,
created_at: 2019-10-22T18:12:50.000Z,
updated_at: 2019-10-22T18:12:50.000Z,
item_id: 1,
category_field_id: 4,
value: 'Iphone',
is_title: 1,
is_description: 0 },
{ id: 3,
category_id: 7,
user_id: 2,
title: '',
image1: '15717679702861gohz24vrk2262fov.jpg',
image2: '15717679702891gohz24vrk2262fox.jpg',
image3: '15717679702911gohz24vrk2262foz.jpg',
image4: '15717679702921gohz24vrk2262fp0.jpg',
image5: '15717679702931gohz24vrk2262fp1.jpg',
status: 2,
created_at: 2019-10-22T18:12:50.000Z,
updated_at: 2019-10-22T18:12:50.000Z,
item_id: 1,
category_field_id: 3,
value: 'Other',
is_title: 0,
is_description: 0 },
{ id: 11,
category_id: 7,
user_id: 2,
title: '',
image1: '15718960965161gohz24rzk24acmit.jpg',
image2: '15718960965181gohz24rzk24acmiu.jpg',
image3: '15718960965191gohz24rzk24acmiv.jpg',
image4: '15718960965201gohz24rzk24acmiw.jpg',
image5: '15718960965221gohz24rzk24acmiy.jpg',
status: 0,
created_at: 2019-10-24T05:48:16.000Z,
updated_at: 2019-10-24T05:48:16.000Z,
item_id: 3,
category_field_id: 3,
value: 'Other',
is_title: 0,
is_description: 0 } ]
i want to group by this on item_id. but only those who have a specific length that is enter by user (number of inputs by user in search)
suppose length is 2 so the item that having only two object included in final result;
like
{
1: [{ id: 4,
category_id: 7,
user_id: 2,
title: '',
image1: '15717679702861gohz24vrk2262fov.jpg',
image2: '15717679702891gohz24vrk2262fox.jpg',
image3: '15717679702911gohz24vrk2262foz.jpg',
image4: '15717679702921gohz24vrk2262fp0.jpg',
image5: '15717679702931gohz24vrk2262fp1.jpg',
status: 2,
created_at: 2019-10-22T18:12:50.000Z,
updated_at: 2019-10-22T18:12:50.000Z,
item_id: 1,
category_field_id: 4,
value: 'Iphone',
is_title: 1,
is_description: 0 },
{ id: 3,
category_id: 7,
user_id: 2,
title: '',
image1: '15717679702861gohz24vrk2262fov.jpg',
image2: '15717679702891gohz24vrk2262fox.jpg',
image3: '15717679702911gohz24vrk2262foz.jpg',
image4: '15717679702921gohz24vrk2262fp0.jpg',
image5: '15717679702931gohz24vrk2262fp1.jpg',
status: 2,
created_at: 2019-10-22T18:12:50.000Z,
updated_at: 2019-10-22T18:12:50.000Z,
item_id: 1,
category_field_id: 3,
value: 'Other',
is_title: 0,
is_description: 0 }
]
}

By default, lodash doesn't provide the feature you need.
Instead, you can try combining _groupBy and _pickBy functions.
var groupedItems = _.groupBy(items, 'item_id');
var userSearchLength = 2;
var filteredGrouping = _.pickBy(groupedItems, function(value, key) {
return value.length == userSearchLength;
});

const userInputNumber = 2;
let grouped =_groupBy(obj,(o)=> o.item_id)
Object.keys(grouped).forEach(item_id=> {
if(grouped[item_id].length !== userInputNumber){
delete grouped[item_id];
}
})
You'll have to group first and then check and delete groups which don't have the length of array you desire.

I hope this will help you.
You can first group the data and then filter the data that you needed.
const givenLength = 2;
const groupData =_.groupBy(data,(o)=> o.item_id);
const filtered = _.filter(groupData, (o) => o.length === givenLength );

Related

How to set header span title in same row using writeXlsxFile excel node

How to set a header title in same row using const writeXlsxFile = require("write-excel-file/node");
HEADER_ROW = [
{
type: String,
value: 'John Smith',
span: 1,
sort: 1
},
{
type: String,
value: 'John Smith',
span: 3,
sort: 2
},
{
type: String,
value: 'John Smith',
span: 6,
sort: 4
}
]

Show/Hide a Formatter on Cell

I have a column setup with a cell formatter and is working fine.
{ title: "MKT Score", field: "MKTScore", width: 110, hozAlign: "center", formatter: "star", formatterParams: { stars: 3 }, },
what I'm look at trying to do is, if a value of a different cell is false is to hide the Formatter on a cell so it would be blank.
For some situations, such as the "star" formatter, you could pass a function to the formatterParams property in order to manupilate the formatter. Here is an example where, if the bool column is false, show blank:
const dataSet1 = [
{ id: 1, name: 'Billy Bob', bool: false, gender: 'male', rating: 2, col: 'red' },
{ id: 2, name: 'Mary May', bool: true, gender: 'female', rating: 3, col: 'blue' },
{ id: 3, name: 'Christine Lobowski', bool: false, gender: 'female', rating: 0, col: 'green' },
{ id: 4, name: 'Brendon Philips', bool: true, gender: 'male', rating: 2, col: 'orange' },
{ id: 5, name: 'Margret Marmajuke', bool: false, gender: 'female', rating: 0, col: 'yellow' }
]
const table = new Tabulator('#table', {
data: dataSet1,
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Bool', field: 'bool' },
{ title: 'Gender', field: 'gender' },
{ title: 'Rating', field: 'rating', formatter: "star" , formatterParams: stars },
{ title: 'Favourite Color', field: 'col' }
]
})
function stars(row) {
return row.getData().bool ? { stars: 3 } : { stars: -1 }
}
<link href="https://unpkg.com/tabulator-tables#5.1.8/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#5.1.8/dist/js/tabulator.min.js"></script>
<div id="table"></div>

Why does my GraphQL/Apollo mutation fail?

This is how the Apollo query is defined:
const createUser = gql`
mutation(
$username: String!,
$email: String!,
$password: String!,
$time_created: String!,
$time_played: Int!,
$verified: Boolean!,
$type_user: Boolean!,
$userLevel: UserLevelInput!,
$ranks: RanksInput!,
$pvp: PvpInput!
){
createUser(
username: $username,
email: $email,
password: $password,
time_created: $time_created,
time_played: $time_played,
verified: $verified,
type_user: $type_user,
userLevel: $userLevel,
ranks: $ranks,
pvp: $pvp
){
username
email
password
}
}
`;
My schema:
const userSchema = new Schema({
username: String,
email: String,
password: String,
time_created: Date,
time_played: Number,
verified: Boolean,
type_user: Boolean,
userLevel: {
lidUnlocked: Number,
gidUnlocked: Number,
},
ranks: {
level: [
{
level: Number,
avgTime: Number,
rank: Number,
group: [
{
group: Number,
time: Number,
rank: Number,
},
],
},
],
},
pvp: {
points: Number,
rank: Number,
},
});
How I'm making the request:
const handleSubmit = (e) => {
e.preventDefault();
addUser({
variables: {
username: input.username,
email: input.email,
password: input.password,
time_created: Date.now(),
time_played: 0,
verified: false,
type_user: false,
userLevel: {
lidUnlocked: 1,
gidUnlocked: 1
},
ranks: {
level: [{
level: 1,
avgTime: 0,
rank: 0,
group: [{
group: 1,
time: 0,
rank: 0
}]
}]
},
pvp: {
points: 0,
rank: 0,
}
}
})
}
UserLevelInput, RanksInput and PvpInput:
const UserLevelInputType = new GraphQLInputObjectType({
name: "UserLevelInput",
fields: () => ({
lidUnlocked: { type: GraphQLInt },
gidUnlocked: { type: GraphQLInt },
}),
});
const RanksInputType = new GraphQLInputObjectType({
name: "RanksInput",
fields: () => ({
level: { type: new GraphQLList(LevelInputType) },
}),
});
const LevelInputType = new GraphQLInputObjectType({
name: "LevelInput",
fields: () => ({
level: { type: GraphQLInt },
avgTime: { type: GraphQLInt },
rank: { type: GraphQLInt },
group: { type: new GraphQLList(GroupInputType) },
}),
});
const GroupInputType = new GraphQLInputObjectType({
name: "GroupInput",
fields: () => ({
group: { type: GraphQLInt },
time: { type: GraphQLInt },
rank: { type: GraphQLInt },
}),
});
const PvpInputType = new GraphQLInputObjectType({
name: "PvpInput",
fields: () => ({
points: { type: GraphQLInt },
rank: { type: GraphQLInt },
}),
});
If i make this mutation on localhost:5005/graphql it works as intended:
mutation{
createUser(
username:"babadany2999",
email:"babadany2999#gmail.com",
password:"Immboold1",
time_created:"1645738406658",
time_played: 0,
verified: false,
type_user: false,
userLevel:{
lidUnlocked: 1,
gidUnlocked: 1
},
ranks: {
level: [{
level: 1,
avgTime: 0,
rank: 0,
group:[{
group: 1,
time: 0,
rank: 0
}]
}]
},
pvp: {
points: 0,
rank: 0
}
), {
username
email
password
}
}
Also if I make the request(with the code not in /graphql) and then check out Apollo Dev tools for that particular mutation, I get that the Int, UserLevelInput, RanksInput and PpvInput types are not known.
Apollo Dev Tools type unknown
For anyone encountering the same problem, I managed to "fix" it by creating constants of the complex objects and simply setting the default to those constants in the mongoose table and not giving that as input to apollo.
username: String,
email: String,
password: String,
time_created: {
type: Date,
default: new Date()
},
time_played: {
type: Number,
default: 0
},
type_user: {
type: Boolean,
default: false
},
verified: {
type: Boolean,
default: false
},
userLevel: {
lidUnlocked: Number,
gidUnlocked: Number
},
ranks: {
type: Object,
default: ranks
},
pvp: {
points: {
type: Number,
default: 0
},
rank: Number
}
})
And part of the constant(it's very long but it has the same structure until the end):
const ranks= {
level: [
{
level: 1,
group: [
{ group: 1, unlocked: true, time: 0, rank: 0 },
{ group: 2, unlocked: false, time: 0, rank: 0 },
{ group: 3, unlocked: false, time: 0, rank: 0 },
{ group: 4, unlocked: false, time: 0, rank: 0 },
{ group: 5, unlocked: false, time: 0, rank: 0 },
{ group: 6, unlocked: false, time: 0, rank: 0 },
{ group: 7, unlocked: false, time: 0, rank: 0 },
{ group: 8, unlocked: false, time: 0, rank: 0 },
{ group: 9, unlocked: false, time: 0, rank: 0 },
{ group: 10, unlocked: false, time: 0, rank: 0 },
{ group: 11, unlocked: false, time: 0, rank: 0 },
{ group: 12, unlocked: false, time: 0, rank: 0 },
{ group: 13, unlocked: false, time: 0, rank: 0 },
],
unlocked: true,
avgTime: 0,
rank: 0,
},

How to convert key - value pair in to array of same key-value pairs

I am working on e-commerce site using nextjs, express, mongoose, nodejs. User has selected items to order. When he wants to view his list, I call the list of items from userSchema. It is list of ordered items which I get in the below given format:
myList: {
createdAt: 2021-03-19T12:03:41.989Z,
isPaid: false,
isDelivered: false,
_id: 605493f4bd3f98bb9bd5366c,
menuId: 3,
userId: 6006018031a53c2d47e01d93,
itemName: 'Masala Khichdi',
itemPrice: 15,
itemSize: 64,
qtty: 2,
itemPic: '/images/food-menu-3#2X.png',
summary: '+918 372 574',
__v: 0
},{
createdAt: 2021-03-19T12:22:23.579Z,
isPaid: false,
isDelivered: false,
_id: 6054c60667a9c2bc7e2522ce,
menuId: 4,
userId: 6006018031a53c2d47e01d93,
itemName: 'Food Menu 4',
itemPrice: 12,
itemSize: 32,
qtty: 1,
itemPic: '/images/food-menu-4#2X.png',
summary: '+123 456 789',
__v: 0
},{
createdAt: 2021-03-19T12:22:23.579Z,
isPaid: false,
isDelivered: false,
_id: 6054c85467a9c2bc7e2522cf,
menuId: 3,
userId: 6006018031a53c2d47e01d93,
itemName: 'Masala Khichdi',
itemPrice: 11,
itemSize: 32,
qtty: 2,
itemPic: '/images/food-menu-3#2X.png',
summary: '+918 372 574',
__v: 0
}
To process further I need to convert the same list to an array as shown below:
myList: [{
createdAt: 2021-03-19T12:03:41.989Z,
isPaid: false,
isDelivered: false,
_id: 605493f4bd3f98bb9bd5366c,
menuId: 3,
userId: 6006018031a53c2d47e01d93,
itemName: 'Masala Khichdi',
itemPrice: 15,
itemSize: 64,
qtty: 2,
itemPic: '/images/food-menu-3#2X.png',
summary: '+918 372 574',
__v: 0
},{
createdAt: 2021-03-19T12:22:23.579Z,
isPaid: false,
isDelivered: false,
_id: 6054c60667a9c2bc7e2522ce,
menuId: 4,
userId: 6006018031a53c2d47e01d93,
itemName: 'Food Menu 4',
itemPrice: 12,
itemSize: 32,
qtty: 1,
itemPic: '/images/food-menu-4#2X.png',
summary: '+123 456 789',
__v: 0
},{
createdAt: 2021-03-19T12:22:23.579Z,
isPaid: false,
isDelivered: false,
_id: 6054c85467a9c2bc7e2522cf,
menuId: 3,
userId: 6006018031a53c2d47e01d93,
itemName: 'Masala Khichdi',
itemPrice: 11,
itemSize: 32,
qtty: 2,
itemPic: '/images/food-menu-3#2X.png',
summary: '+918 372 574',
__v: 0
} ]
How to do this in backend using nodejs
what is your mongoose query? if you are retrieving data according to userId.
Add .toArray() method in your query.

Removing an objectID of an object in an array with Mongoose

I have the following in my clan scheme
var ClanScheme = new mongoose.Schema
({
name: {type: String, unique: true},
members:
[
{
user: {type: mongoose.Schema.Types.ObjectId, ref:'User', unique: true},
wins: {type: Number, default: 0},
losses: {type: Number, default: 0}
}
],
How do I remove a user from the clan? I've tried a few methods this looking like the least code:
clan.members.remove({'user':userObj._id});
clan.save(function(err)
It seems to run, but the user sticks in the document..
Clan
{ _id: 55e5e8d017e055495dcc3643,
name: 'DBz',
__v: 9,
rating: 1000,
losses: 0,
wins: 0,
rank: 0,
members:
[ { user: [Object],
_id: 55e5e8d017e055495dcc3644,
losses: 0,
wins: 0 },
{ user: [Object],
_id: 55e5eb0f17e055495dcc3645, //<< 55e4ac0340f964d52f8e7fb7
losses: 0,
wins: 0 } ] }
User
{ _id: 55e4ac0340f964d52f8e7fb7,
facebookid: '999',
name: 'Joe Blogs',
__v: 0,
lastDevice: { device: 'Desktop', id: 'adsbr2fjui33emk9p6gtnfrulv' },
multiplayer:
{ clanid: 55e5e8d017e055495dcc3643,
powers: [],
world_commander: 0,
losses: 0,
wins: 0,
clanname: 'DBz',
rating: 1000,
rank: 0,
username: 'Joe' },
saveDataSeed: 40wq211,
saveData: 'yuV2hVJA00zYGm'}
Use a filter function and save.
clan.members = clan.members.filter(function(member){
return String(member.user._id) !== String(userObj._id);
});
clan.markModified('members');
clan.save(function(err)

Resources