compare arrays returning different results javascript - javascript

How do i compare 2 arrays returning different results:
responseFields=[
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true }
]
eventFields=AdditionalFields {
company: BoolValue { value: true },
phone: BoolValue { value: true },
mobile: BoolValue { value: true },
country: BoolValue { value: true }
}
following is what i tried to compare each field but it failed
for (const { field } of responseFields) {
expect(field).to.eql(Object.keys(eventFields)[field]);
}

Related

Fetching documents from DB using a prop which is an object id

I get no results, and I don't know why. (DB has documents with this owner id)
As you can see, I've tried using Types.ObjectId but no success yet.
export const getStores = async (
{ owner, platform }: {
owner: string
platform?: string
}): Promise<StoreMainInfo[]> => {
console.log('owner', owner); // owner 62210e86f36af71f58022971
const stores = await StoreModel.aggregate([
{
'$project': {
'_id': 1,
'platform': 1,
'name': 1,
'category': 1,
'logo': 1,
'urls': 1,
'stats': 1,
}
}, {
$match: { owner: Types.ObjectId(owner) }
},
]);
if (!stores.length) {
throw ApiError.BadRequest('Stores not found.');
}
return stores;
};
// Model:
const StoreSchema: Schema = new Schema({
owner: { type: Types.ObjectId, ref: CollectionNames.user, required: true },
platform: { type: String, required: true },
name: { type: String, required: true },
category: { type: String, required: false },
logo: { type: LogoSchema, required: false },
urls: { type: UrlsSchema, required: true },
stats: { type: StatsSchema, required: true },
suppliers: { type: [SupplierSchema], required: true },
})
export default model<Document & Store>(CollectionNames.store, StoreSchema)

Compare array of object with an array

I have a request
const request=additionalFields: [
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true }
]
the response i am getting is this
"additionalFields":
{
'PHONE':true,
'COMPANY':true,
'MOBILE':true,
'COUNTRY':true
}
i am not sure how to compare them. i kind of wrote something but even to me it looks wrong
const fields = request["additionalFields"];
for (let i = 0, len = fields.length; i < len; i++) {
expect(request.additionalFields[i].required).to.eql(
response.additionalFields
);
Here's another way. Just filter out anything that doesn't match up, then you'll have an array of differences if there are any.
const request={
additionalFields: [
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true }
]
}
const incoming = {
"additionalFields": {
'PHONE': true,
'COMPANY': true,
'MOBILE': false,
'COUNTRY': true
}
}
let differences = request.additionalFields.filter(f => incoming.additionalFields[f.field] !== f.required)
console.log(differences)
const request = [
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true }
]
const response = {"additionalFields":
{
'PHONE':true,
'COMPANY':true,
'MOBILE':true,
'COUNTRY':true
}}
for (const [key, value] of Object.entries(response['additionalFields'])) {
const {required, field} = request.find(({field}) => key === field);
if(required === value) { // here you can compare
console.log(key, field, value);
}
}
You need to dereference the response.additionalFields object using the value of field from each entry in request.additionalFields. Something like
for(const { field, required } of request.additionalFields) {
expect(required).to.eql(
response.additionalFields[field]
);
}
You should loop over each field detail in the request and compare the value against the response. Here you go:
const request = {
additionalFields: [
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true },
],
};
const response = {
additionalFields: {
PHONE: true,
COMPANY: true,
MOBILE: true,
COUNTRY: true,
},
};
for (let f of request.additionalFields) {
// Observe f is like { field:'PHONE', required: true }
// Next two lines are just for test, please remove and uncomment last one in your use case.
const comparisonResult = f.required === response.additionalFields[f.field];
console.log(`for field ${f.field}, It's ${comparisonResult}`);
// expect(f.required).to.eql(response.additionalFields[f.field]);
}
You can further improve readability by using destructuring, drop a comment if you want to see that.
You can use the for...of syntax to do this.
Here's the documentation.
const request = {
additionalFields: [
{ field: 'PHONE', required: true },
{ field: 'COMPANY', required: true },
{ field: 'MOBILE', required: true },
{ field: 'COUNTRY', required: true }
]
};
const response = {
additionalFields: {
PHONE:true,
COMPANY:true,
MOBILE: true,
COUNTRY:true
}
}
const requestFields = request['additionalFields'];
const responseFields = response['additionalFields'];
for(const { required, field } of requestFields) {
expect(required).to.eql(responseFields[field]);
}

Find documents by object field inside array

I gotta a Show Schema and I want to get only avaible tickets inside a show. I need to find all documents that has availableTickets > 0 and get only this subdocuments with the show._id and show.title. How could I do it ?
// Show's Model
const mongoose = require('../../database/mongoose')
const ShowSchema = mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
startsAt: { type: Date, required: true },
endsAt: { type: Date, required: true },
openToBuyAt: { type: Date, required: true },
closedToBuyAt: { type: Date, required:true },
status: { type: Boolean, required: true },
sectors: [{
name: { type: String, required: true },
price: { type: Number, required: true },
availableTickets: { type: Number, required: true }
}],
convenienceFee: { type: Number, required: true },
images: [
{ type: String }
]
})
module.exports = mongoose.model('Show', ShowSchema)
Expected Result
{
"status": "success",
"tickets": [
{
"show._id": "ddadadas12a",
"show.title": "Crazy Show",
"sectors": [
{
"name": "VIP"
"price": 50.25,
"availableTickets": 12
},
{
"name": "General Sector"
"price": 20.00,
"availableTickets": 5
}
]
}
]
}
Unfortunately you have wrong schema.
You don't have "Available tickets" field. if you had any fields like say availableTickets
You could do this in easy way like this:
There are two main parts in this query:
Condition
Project fields: 0/1
ShowSchema.find({availableTickets : { $gt: 0 }}, { title: 1, description: 0, startsAt: 0, endsAt: 0, openToBuyAt: 0, closedToBuyAt: 0, status: 0, sectors:1, convenienceFee:0, images:0, })

How do I access the data in the .pre('validation') hook?

I am having trouble with performing operations during the pre('validate') hook. I need to do some prevalidation (making sure at least one of 2 different fields is populated, but not necessarily both, for example).
const AccessorySchema = new Schema({
accessory: {
type: String,
required: true,
},
category: {
type: String,
required: true,
enum: [
'Offense',
'Defence',
'Miscellaneous'
]
},
space: {
type: Number,
required: true,
validate: {
validator: Number.isInteger,
message: 'Space must be an integer'
}
},
priceFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Price must be an integer'
}
},
priceMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
weightFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Weight must be an integer'
}
},
weightMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
vehicles: {
type: [String],
required: true,
enum: ["car","cycle"]
}
});
AccessorySchema.pre('validate', (next) => {
console.log(this);
next();
});
And I send it this object :
{
accessory: "some name",
category: "Miscellaneous",
priceMultiplier: [3,5],
weightMultiplier: [3,5],
space: 0,
vehicles: ["car"]
}
this logs {} and populates the mongo DB. But I can't check any of the properties in pre validation.
mongoose version is ^4.7.7, nodejs 6.10.2, mongodb version is 3.2.9
How can I access the data in the pre validation hook?
do not use arrow function, it doesn't bind the context.
Change your code to below
AccessorySchema.pre('validate', function(next){
console.log(this);
next();
});

Kendo grid refresh issue in mobile

I refresh the kendo grid for every 10 seconds, I used following code and I used the kendo.all.min.js
$(document).ready(function () {
loadData();
intervalManager(true, TableStatus, 10000);
});
var TableStatus = function () {
loadData();
}
var refreshorderplacedgrid;
function intervalManager(flag, animate, time) {
if (flag)
refreshorderplacedgrid = setInterval(animate, time);
else
clearInterval(refreshorderplacedgrid);
}
function loadData() {
var grid = $("#grid").kendoGrid({
dataSource: {
data: [
{ ID: '1001', FirstName: 'Alphy', LastName: 'LastName', category: 'A', Markable: true },
{ ID: '1002', FirstName: 'Betty', LastName: 'LastName', category: 'B', Markable: true}],
schema: {
model: {
fields: {
FirstName: { type: "string" },
LastName: { type: "string" }
}
}
},
sort: {
field: "FirstName",
dir: "asc"
},
pageSize: 10
},
scrollable: true,
sortable: true,
selectable: true,
columns: [
{
field: "FirstName",
title: "First Name"
},
{
field: "LastName",
title: "Last Name"
},
{ template: kendo.template($("#isCancel-template").html()) }
]
}).data("kendoGrid");
}
This code gives me the output like following screenshot in system chrome,
But in mobile [All devices]
It appends with the old grid, instead of rebinding like following screenshot
I dont know what is problem here, I have googled and used $("#grid").data("kendoGrid").refresh(); this code too. Nothing happend, Any help will be highly appreciable.
Thanks,
Guna
#gitsitgo 's comment, I changed the code as following way, for avoid the re initialization of the grid, and now its working fine.
var myDataSource = new kendo.data.DataSource({
data: [
{ ID: '1001', FirstName: 'Alphy', LastName: 'LastName', category: 'A', Markable: true },
{ ID: '1002', FirstName: 'Betty', LastName: 'LastName', category: 'B', Markable: true },
{ ID: '1003', FirstName: 'Betty', LastName: 'LastName', category: 'B', Markable: true}],
schema: {
model: {
fields: {
FirstName: { type: "string" },
LastName: { type: "string" }
}
}
},
sort: {
field: "FirstName",
dir: "asc"
},
pageSize: 10
});
$(document).ready(function () {
initGrid();
loadData();
intervalManager(true, TableStatus, 10000);
});
var TableStatus = function () {
loadData();
}
var refreshorderplacedgrid;
function intervalManager(flag, animate, time) {
if (flag)
refreshorderplacedgrid = setInterval(animate, time);
else
clearInterval(refreshorderplacedgrid);
}
function loadData() {
$("#grid").data("kendoGrid").setDataSource(myDataSource);
$("#grid").data("kendoGrid").refresh();
}
function initGrid() {
var grid = $("#grid").kendoGrid({
dataSource: myDataSource,
scrollable: true,
sortable: true,
selectable: true,
columns: [
{
field: "FirstName",
title: "First Name"
},
{
field: "LastName",
title: "Last Name"
},
{ template: kendo.template($("#isCancel-template").html()) }
]
}).data("kendoGrid");
}
Thanks,
Guna

Categories

Resources