Javascript Object transformation/flat - javascript

My goal is to use create schema for json-schema-yup-transformer, therefore, I need to get this format :
const schema = {
type: "object",
properties: {
firstName: {
type: "string",
minLength: 2,
},
email: {
type: "string",
format: "email",
},
},
required: requiredFields,
};
I've got a schemaProperties :
const schemaProperties = formatData.map((item) => {
return {
[item.value]: { type: item.type, validation: item.validation },
};
});
That returns me :
[
{
"firstName": {
"type": "text",
"validation": {
"required": true,
"requiredMessage": "Prénom requis"
}
}
},
{
"lastName": {
"type": "text"
}
},
...
]
But, my problem is that schemaProperties is an array actually and not an object. I tried to destruct it and transform into an object, but its not working... Im sure its not something very complicated but I'm stuck...

Related

Mongoose, updated nested array

My question is:
How can I query in the nested arrays?
I want to change value in key "likeUp" which is nested inside object in array "usersWhoLiked". Where "usersWhoLiked" is nested in array "comments"
How Can I do that with mongoose ?
Request that I wrote beneath... do not work, but is very similar to answer given in StackOverflow post: Mongoose update update nested object inside an array
This is my request to db with updateOne:
try {
const response = await Comments.updateOne(
{
productId,
comments: { $elemMatch: { usersWhoLiked: { $elemMatch: { userId } } } },
},
{
$set: { 'comments.$[outer].usersWhoLiked.$[inner].likeUp': likes.up },
},
{
arrayFilters: [{ 'outer._id': commentId }, { 'inner._userId': userId }],
}
).exec();
return res.status(201).json({ response });
} catch (err) {
console.log(err);
return res.send(err);
}
This is the collection, that I am trying to update:
{
"_id": {
"$oid": "6307569d2308b78b378cc802"
},
"productId": "629da4b6634d5d11a859d729",
"comments": [
{
"userId": "62f29c2c324f4778dff443f6",
"userName": "User",
"date": "2022.08.25",
"confirmed": true,
"likes": {
"up": 0,
"down": 0
},
"content": {
"rating": 5,
"description": "Nowy komentarz"
},
"_id": {
"$oid": "630756b22308b78b378cc809"
},
"usersWhoLiked": [
{
"userId": "62f29c2c324f4778dff443f1",
"likeUp": true,
"_id": {
"$oid": "6307572d2308b78b378cc80e"
}
},
{
"userId": "62f29c2c324f4778dff443f2",
"likeUp": true,
"_id": {
"$oid": "6307572d2308b78b378cc80c"
}
}
]
}
],
"__v": 0
}
Mongooes schema for comment collection:
const commentSchema = new Schema({
productId: String,
comments: [
{
userId: String,
userName: String,
date: String,
confirmed: Boolean,
likes: {
up: {
type: Number,
default: 0,
},
down: {
type: Number,
default: 0,
},
},
content: {
rating: Number,
description: String,
},
usersWhoLiked: [{ userId: String, likeUp: Boolean }],
},
],
});
I guess the problem is with your arrayFilters operator, because you are trying to filter by field _userId which does not exist:
arrayFilters: [{ 'outer._id': commentId }, { 'inner._userId': userId }],
I managed to update the likeUp value using the following query:
db.collection.update({
_id: ObjectId("6307569d2308b78b378cc802")
},
{
$set: {
"comments.$[user].usersWhoLiked.$[like].likeUp": false
}
},
{
arrayFilters: [
{
"user._id": ObjectId("630756b22308b78b378cc809")
},
{
"like.userId": "62f29c2c324f4778dff443f1"
}
]
})
Try it on MongoDB playground: https://mongoplayground.net/p/XhQMNBgEdhp

MongooseJS: How to remove 1 object inside Array in Array of Objects

Hi MongooseJS experts!
I'm new in MongooseJS, This is my 2nd day of solving this problem but I can't find a working solution to this.
Thank you in advance!
My Delete method
Cart.updateOne(
{ "content.merchantId": req.body.merchantId },
{ $pull: { "content.items._id": req.body.productId } },
{ new: true },
function (error, result) {
if (error) { }
else if (result) { }
}
);
Schema
const CartSchema = new Schema({
customerId: {
type: String,
required: true,
},
content: {
merchantName: {
type: String,
required: true,
},
merchantId: {
type: String,
required: true,
},
items: [],
},
});
Sample JSON
[
{
"content": {
"merchantName": "SAMPLE_MERCHANT_NAME",
"merchantId": "SAMPLE_MERCHANT_ID",
"items": [
{
"_id": "SAMPLE_ID",
"title": "SAMPLE TITLE",
}
]
},
"_id": "618220e83966345ab5d451cd",
"__v": 0
},
]
Error message
Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [{ _id: "SAMPLE_ID", title: "SAMPLE TITLE"}] })
you should use like this
db.collection.update({
"content.merchantId": "SAMPLE_MERCHANT_ID"
},
{
$pull: {
"content.items": {
"_id": "SAMPLE_ID"
}
}
},
{
new:true
},
)
https://mongoplayground.net/p/Ou26tab2mBU

Meteor AutoForm adding users to select

I know I am close on this, but just cant seem to sort out what I am missing.
I am trying to add all users as options to a select in an autoform quickform. I was able to get it working with another collection, but when I use the same code for the users the value shows up as the _id but I cannot get the label to return.
Here is the structure of my users:
{
"_id": "s3EYXXK5N8NExHrke",
"emails": [{
"address": "admin#gmail.com",
"verified": false
}],
"profile": {
"firstName": "Joe",
"lastName": "Smuck",
"licenseNumber": "1234567",
"accountType": "administrator"
},
"roles": [
"administrator"
],
"createdAt": "2016-12-02T21:51:11.844Z",
"services": {
"password": {
"bcrypt": "$2a$10$NheMU2x/8RvcMxNHeWxbQOpHlWAQmopvk3KrMG9oo5ruTir2ARf8W"
},
"resume": {
"loginTokens": [{
"when": "2016-12-02T21:51:11.948Z",
"hashedToken": "8PktpX6kqK6yM+LMrqRaoqXCbwYG6gdO7MH9V/Th/dI="
}, {
"when": "2016-12-03T03:01:06.600Z",
"hashedToken": "ihn93xaN6rE8fvwBHZ3p8H6z0T7o7WChQoqD4dlkSpw="
}, {
"when": "2016-12-05T14:37:41.147Z",
"hashedToken": "7QE7HxcmDrZPFI3Omn5c1o73pMa3XzOBj3RbquCmo6U="
}]
}
}
}
I am trying to print the firstName to the select. Here is the schema I have now:
inspector: {
type: String,
label: "Inspector",
autoform: {
firstOption: 'Choose an Inspector',
options: function() {
return Meteor.users.find({}, {
sort: {
profile: 1,
firstName: 1
}
}).map(function(c) {
return {
label: c.firstName,
value: c._id
};
});
}
}
},
I would appreciate any help someone can offer!
To tie this off it should have been:
inspector: {
type: String,
label: "Inspector",
autoform: {
firstOption: 'Choose an Inspector',
options: function() {
return Meteor.users.find({}, {
sort: {
profile: 1,
firstName: 1
}
}).map(function(c) {
return {
label: c.profile.firstName,
value: c._id
};
});
}
}
},

Unable to reference GraphQLObjectType while creating it

I'm trying to dynamically generate a graphql scheme from a json config. But i'm unable to create a GraphQLList to itself.
json:
{
"label": "user",
"properties": [
{
"key": "name",
"type": "string"
},
{
"key": "id",
"type": "id"
},
{
"key": "birthday",
"type": "date"
},
{
"key": "gender",
"type": "string"
},
{
key: 'friends',
type: 'string'
}
]
}
The javascript code generating:
graphSchemes.forEach(function (graphScheme) {
graphQLObjects[graphScheme.label] = new graphql.GraphQLObjectType({
name: graphScheme.label,
fields: graphScheme.properties.reduce((fields, property) => {
if (property.key === 'friends') {
fields[property.key] = {
type: new graphql.GraphQLList(graphQLObjects[graphScheme.label])
};
return fields;
}
fields[property.key] = {
type: TYPES[property.type]
};
return fields;
}, {})
});
});
The issue here is:
type: new graphql.GraphQLList(graphQLObjects[graphScheme.label])
There is no "graphQLObjects[graphScheme.label]"
How can I go around this? Any suggestions?
It's possible a field to reference the type itself by putting the fields in a wrapper function.
an example:
var routeType = new GraphQLObjectType({
name: 'MessageRoute',
fields: function () {
return {
name: {
type: GraphQLString
},
routes: {
type: new GraphQLList(routeType),
resolve: (route) => {
return route.routes;
}
}
};
}
});

How to verify an observable object have all the required members?

Basically I want to validate my observable before apply the bindings, so that I will never get that something something is not defined error.
Say I do have a javascript class that defines all that I need, and I want to validate an observable created from ajax against it.
Is there a generic way to do it?
Edit:
http://jsfiddle.net/rgneko/GuR8v/
Currently the demo will throw error because one of the items has no id property. I want to verify whether all items are valid.
$(document).ready(function () {
function ModelToTestAgainst(id, name, type, items) {
this.id = id;
this.name = name;
this.type = type;
this.items = items;
}
var data = {
items: [{
id: 1,
name: 'name1',
type: 'folder',
items: []
}, {
id: 2,
name: 'name2',
type: 'file',
items: []
}, {
name: 'name2',
type: 'file',
items: []
}]
};
var someRandomObservaleIGotFromWherever = ko.mapping.fromJS(data);
// I want to Validate(someRandomObservaleIGotFromWherever) before apply bindings
ko.applyBindings(someRandomObservaleIGotFromWherever);
});
There is a standard JSON Schema, defined in http://json-schema.org/.
An schema can be as simple as:
var schema = {"type" : "object"};
which requires the value to be an object. Or much more complex, like this example from json-schema.org:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
which requires several properties to exists, defines their types, and even a minimun value for one of them.
Then you need a library that allows to validate the JS objects with this kind of schema. In the same site, you can find a list of libraries for validating (and parsing, creating documentation...). Note that not all libraries are updated, and not all of them support the latest JSON schema version.
For example, using JSV, you can make a validation simply like this:
var report = env.validate(json, schema);
Why don't you map/wrap it into a view model that you know has all the properties that you need?
function ViewModel(model) {
this.x = ko.observable(model.x || 0);
this.y = ko.observable(model.y || 0);
}
var original = { x: 27 }; // Use your ajax object here.
var viewModel = new ViewModel(original);
What about using JSON Schema validation.
I have used library from Tiny Validator to enable validation. Validation is easy to add as an observable extension
$(document).ready(function () {
// Attach a validationSchema method to all observable types
ko.subscribable.fn["validateSchema"] = function(schema){
// Convert the observable back to an object literal to test.
var source = ko.mapping.toJS(this());
return tv4.validate(source, schema);
};
// Define schema for ModelToTestAgainst
var modelSchema = {
"$schema": "http://tempuri.org/ModelToTestAgainst",
"title": "ModelToTestAgainst Set",
"type": "array",
"items": {
"title": "ModelToTestAgainst",
"type": "object",
"properties" : {
"id" : {
"type": "number",
"minimum" : 1
},
"name" : { "type": "string" },
"type" : { "type": "string" },
"items" : { "type" : "array" }
},
"required": ["id", "name", "type", "items"]
}
};
function ModelToTestAgainst(id, name, type, items) {
this.id = id;
this.name = name;
this.type = type;
this.items = items;
}
var data = {
items: [{
id: 1,
name: 'name1',
type: 'folder',
items: []
}, {
id: 2,
name: 'name2',
type: 'file',
items: []
}, {
name: 'name2',
type: 'file',
items: []
}]
};
var obs = ko.mapping.fromJS(data));
var isValid = obs.items.validateSchema(modelSchema);
if( isValid ) {
ko.applyBindings(obs);
}
});

Categories

Resources