Meteor AutoForm adding users to select - javascript

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
};
});
}
}
},

Related

Javascript Object transformation/flat

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...

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

Filtering objects array by nested values

I'm trying to filter this objects array and keep the original one aside.
{"departments":
[
{
“name": “AAA",
“selected”: true,
"courses": [
{
"name": “course1",
“selected”: true,
“titles”:
[{
"name": “title1",
“selected”: true
},
{
"name": “title2",
“selected”: false
}]
},
{
"name": “course2",
“selected”: false,
“titles”:
[{
"name": “title1",
“selected”: false
}]
}
]
},
{
“name": “BBB",
“selected”: false,
"courses": [{...}]
{...}
]
}
I want to find all the selected departments, courses and titles. And it should be in the same format.
I tried with below code, but it change original data. I want to keep that aside too.
const depts = departments.filter((dept: any) => {
if (dept.selected) {
dept.courses = dept.courses.filter((course: any) => {
if (course.selected) {
if (course.titles) {
course.titles = course.titles.filter(({selected}: any) => selected);
}
return true;
}
return false;
});
return true;
}
return false;
});
What would be considered the best solution in this case?
Shorter alternative can be to use the JSON.parse reviver parameter :
var arr = [{ name: "AAA", selected: true, courses: [{name: "course1", selected: true, titles: [{ name: "title1", selected: true }, { name: "title1", selected: false }]}, { name: "course2", selected: false, titles: [{ name: "title1", selected: false }]}]}]
var result = JSON.parse(JSON.stringify(arr), (k, v) => v.map ? v.filter(x => x.selected) : v)
console.log( result )
your filtering logic seems to be correct. only problem is that code changes original array. in order to overcome this problem just create a deep clone of original array and run filtering logic on it
filterArray() {
const clone = JSON.parse(JSON.stringify(this.departments));
const depts = clone.filter((dept: any) => {
if (dept.selected) {
dept.courses = dept.courses.filter((course: any) => {
if (course.selected) {
if (course.titles) {
course.titles = course.titles.filter(({ selected }: any) => selected);
}
return true;
}
return false;
});
return true;
}
return false;
});
console.log(depts);
}
here is a demo https://stackblitz.com/edit/angular-xx1kp4
const filterSelected = obj => {
return {
...obj,
departments: obj.departments.map(dep => {
return {
...dep,
courses: dep.courses.map(course => {
return {
...course,
titles: course.titles.filter(title => title.selected),
};
}).filter(course => course.selected),
};
}).filter(dep => dep.selected),
};
}
const all = {
departments: [
{
name: "AAA",
selected: true,
courses: [
{
name: "course1",
selected: true,
titles: [
{
name: "title1",
selected: true
}, {
name: "title1",
selected: false
}
]
}, {
name: "course2",
selected: false,
titles: [
{
name: "title1",
selected: false
}
]
},
]
}
]
};
console.log(filterSelected(all));
I don't know if you prefer an API false. Here is my tip:
You can to use an API Json Server.
Install JSON Server
npm install -g json-server
Create a db.json file with some data
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
Start JSON Server
json-server --watch db.json
Now if you go to http://localhost:3000/posts/1, you'll get
{ "id": 1, "title": "json-server", "author": "typicode" }
you can search your array of objects using various shapes and it will come filtered. More about the API here: https://github.com/typicode/json-server
(Use a filter to do your searches on the Angular, it will bring you right what you need, use a method inside your component)

How to perform match query in Elasticsearch in Node.js?

I wrote an Elaticsearch query for match category and name in my records.
My sample record:
{category: "disease", name: "Heart Diseases", dui: "D006331", url_name: "Heart Disease"}
I need to match my parameter with 'name' and category should be 'disease' and 'hospital' always and wrote it like this:
match: {
name: {
query: searchString,
fuzziness: 2,
operator: "or"
},
category: ['hospital', 'disease']
}
Updated code:
client.search({
index: 'xpertdox',
type: 'disease',
size: 20,
body: {
query: {
bool: {
must: {
match: {
name: {
query: req.param('disease'),
//fuzziness:"AUTO",
fuzziness: 2,
operator: "or"
}
}
},
should : [
{ term : { category: disease} }
],
minimum_should_match: 2
}
}
But this is not working. I don't know where the mistake is.
To match all categories is one doc use query below
{
"query": {
"bool": {
"must": {
"match": {
"name": {
"query": searchString,
"fuzziness": 2,
"operator": "or"
}
}
},
"should": [
{ "term": { "category": "hospital" } },
{ "term": { "category": "disease" } }
],
"minimum_should_match": 2
}
}
}
minimum_should_match should be equal to the number of optional clauses (the clauses in "should" array).
UPDATE
To match one category from the list of categories, use filter and terms query
{
"query": {
"bool": {
"must": {
"match": {
"name": {
"query": searchString,
"fuzziness": 2,
"operator": "or"
}
}
},
"filter": {
"terms": { "category": [ "hospital", "disease"] }
}
}
}
}

Categories

Resources