How to use select on azure search suggesters - javascript

I'm using Azure search on my project, and I want to do an autocomplete text field, it works as expected. here's the code :
const suggestItems = async (req, res) => {
try {
// Reading inputs from HTTP Request
const q = (req.query.q || (req.body && req.body.q));
const top = (req.query.top || (req.body && req.body.top));
const suggester = (req.query.suggester || (req.body && req.body.suggester));
// Let's get the top 5 suggestions for that search term
const suggestions = await client.suggest(q, suggester, { top: parseInt(top) });
//const suggestions = await client.autocomplete(q, suggester, {top: parseInt(top)});
console.log(suggestions.results)
return res.status(status.OK)
.json({ suggestions: suggestions.results})
} catch (error) {
handleError(res, error)
}
}
her's the result :
[
{ text: 'Alpha Aromatics (MA)', document: { id: '4' } },
{ text: 'Alpha Aromatics (USA)', document: { id: '5' } },
{ text: 'Art Land - Winter Palace', document: { id: '6' } },
{ text: 'Alpha Aromatics (USA)', document: { id: '3' } }
]
here's the quesry passed by postman :
{
"q":"ar","top":5,"suggester":"sg"
}
but the problem is , on the result I have just the text and the id of the document , I'm looking for other fields like status for example, how can get that please ?

I am guessing "Status" is one of your index fields, from the question. You need to make sure you mark the fields you need to be returned in the results as retrievable in your index definition. It looks you only have text and id fields as retrievable. For more information: https://learn.microsoft.com/en-us/azure/search/search-what-is-an-index.
Example:

Related

Am trying to update a database in sequelize

I am trying to update a sequelize database, where the fields that need to be updated is optional. The problem is that I have 3 fields that need to be updated which are all optional. I do not want to check each field one by one calling update method. Cause that will mean multiple call to the api. Sample raw body input in JSON
{
"authorIds": [1, 5],
"tags": ["tech", "health"],
"text": "Some very short blog post text here."
}
Any of these fields can be optional. This is what I have so far
const { authorIds, tags, text } = req.body;
// case where all fields came in
if (authorIds && tags && text) {
try {
const ids = authorIds.join(',');
const tagValue = tags.join(',');
await Post.update(
{ authorIds: ids, tags: tagValue, text: text },
{ where: { id: postId } }
);
} catch (error) {
res.json({ error: 'Please check your body format' });
}
}
Note I am using SQLite, so I can not store arrays, that why am making the inputs. into string
Thanks
You can easily construct an object that you need to pass as the first argument to update dynamically:
if (authorIds || tags || text) {
try {
const fieldsToUpdate = {}
if (authorIds && authorIds.length) {
const ids = authorIds.join(',');
fieldsToUpdate.authorIds = ids;
}
if (tags && tags.length) {
const tagValue = tags.join(',');
fieldsToUpdate.tags = tagValue;
}
if (text) {
fieldsToUpdate.text = text;
}
await Post.update(
fieldsToUpdate,
{ where: { id: postId } }
);
} catch (error) {
res.json({ error: 'Please check your body format' });
}
}
Also you can try to use object deconstruction along with ternary operators to combine all fields right in the update call.
...(authorIds && authorIds.length ? { authorIds: authorIds.join(',') } : {}).

How to display search result with mongoose pagination

I have Training Collection with lots of data. All function works except that on search result the latest entry results appear correctly, but the old results don't appear on front except they appear on the pages based on their position. Helper and course are populated from another schema. The reason I used the if condition is because the helper and course are populated. I tried searching for similar problem on stack overflow and other website and tried to query it as 'helper.first_name': { $regex: reg_ex } but it did not work for me that way. Here is the pseudo code below
P.s I am using pagination. I need help please
req.checkBody('search').notEmpty().withMessage('Please enter a query'); // check empty entry
const reg_ex = new RegExp(req.body.search, 'i'); // regular expression
const page = parseInt(req.query.page);
const limit = 20;
const skipIndex = (page - 1) * limit;
try {
Training
.find()
.populate([{
path: 'helper',
model: Helper
},
{
path: 'course',
model: Course
},
{
path: 'user',
select: '-password'
}
])
.sort({
_id: -1
})
.limit(limit)
.skip(skipIndex)
.exec(function (err, doc) {
if (err) {
return next(err)
}
const arryPush = [];
doc.forEach(data => {
if (
(data.batch.match(reg_ex) != null) ||
(data.helper.first_name.match(reg_ex) != null) ||
(data.helper.last_name.match(reg_ex) != null) ||
(data.helper.phone.match(reg_ex) != null) ||
(data.helper.email.match(reg_ex) != null) ||
(data.course[0].title.en.match(reg_ex) != null)
) {
arryPush.push({
_id: data._id,
course: [{
title: {
en: data.course[0].title.en,
am: data.course[0].title.am
}
}],
is_rejected: data.is_rejected,
approved: data.approved,
training_completion_status: data.training_completion_status,
training_time: data.training_time,
weekdays: data.weekdays,
payment_option: data.payment_option,
batch: data.batch,
created_at: data.created_at,
helper: {
first_name: data.helper.first_name,
last_name: data.helper.last_name,
phone: data.helper.phone,
email: data.helper.email
}
})
}
});
res.status(200).json(arryPush)
});
} catch (e) {
res.status(500).json({
message: "Error Occured" + e
});
}

Can't push selected items in array - Angular material mat select multiple

Could someone help me to identify where im doing wrong when pushing data to empty array?
So, Am trying to push only selected values (i.e only checked true). but i cant go inside the loop
condition i had now
const vals = [];
if (e && e.source.selected.length > 0) {
console.log('selected values', e.source.selected);
const sel = e.source.selected;
sel.forEach((e: any) => {
if (sel._selected) {
vals.push(e);
console.log('EE', e);
}
});
}
demo blitz
expected:
selectedList : [
{ id: '0' }, { id: '1' }, { id: '2' }
]
Purpose:
trying to bind same data in edit mode in form
You don't need your function at all. Remove it completely and instead do
console.log(e.source.value);
It automatically contains all selected values !
Each time you make an update the array will be updated as well to contain only the selected values.
If you want to transform it
expected:
selectedList : [ { id: '0' }, { id: '1' }, { id: '2' } ]
then just do
let selectedList = e.source.value.map((elem: number) => ({ id: elem }));
console.log(selectedList);
Try this
onSelectingToppings(e: any) {
const vals:any[] = [];
if (e && e.source.selected.length > 0) {
// console.log('selected values', e.source.selected);
const sel = e.source.selected;
sel.forEach((item: any) => {
if (item._selected) {
vals.push(item);
}
});
console.log(vals.length)
}
}
Looks like your if condition is wrong, the corrected version should be as below:
const vals = [];
if (e && e.source.selected.length > 0) {
console.log('selected values', e.source.selected);
const sel = e.source.selected;
sel.forEach((e: any) => {
if (e.selected) {
vals.push({"id": e.value});
console.log('EE', {"id": e.value});
}
});
}
Unless you are trying something different. You could try putting a console statement before your if condition inside loop to check what was going wrong.
Add optional chaining to prevent error when no value selected/page initialized. Then sel holds the the array of selected values. See below for updated code
if (e && e.source?.selected?.length > 0) {
console.log('selected values', e);
const sel = e.source.selected;
sel?.value?.forEach((e: any) => {
vals.push(e);
console.log('EE', e);
});
}

Discord.js - DiscordAPIError: Invalid Form Body embed.fields[0].value: This field is required Error

i have been trying to make an order command for my discord.js bot when someone uses the command it doesn't respond and says this error in the console "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
DiscordAPIError: Invalid Form Body
embed.fields[0].value: This field is required" however i have been trying to fix it but i can't see whats wrong with the code the code for the command is
const colors = require("colors");
function generateID() {
let ticketGen = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split("");
let ticketStr = "";
for(let i = 0; i < 3; i++) {
ticketStr += ticketGen[Math.floor(Math.random() * ticketGen.length)];
}
return ticketStr;
}
exports.id = "order";
exports.onLoad = api => {
api.commands.add("order", (msg) => {
// The order.
let order = msg.content.substring(8);
let customer = msg.author.id
fsn.readJSON("./blacklist.json").then((blacklistDB) => {
let entry = blacklistDB[msg.guild.id];
// Checks is server is blacklisted or not.
if(entry === undefined) {
// Gets ticket ID.
const ticketID = generateID();
// Sends ticket information to tickets channel.
api.client.guilds.get("745409671430668389").channels.get("746423099871985755").send({embed: {
color: 0xFFFFFF,
title: msg.author.username,
fields: [{
name: "Order Description",
value: order,
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Order Status",
value: ticketID,
}],
timestamp: new Date(),
footer: {
text: `From ${msg.guild} (${msg.guild.id})`
}
}}).then((m) => {
m = m.id;
// Sets ticket info.
fsn.readJSON("./orders.json").then(orderDB => {
// Set JSON information.
if (!orderDB[ticketID]) orderDB[ticketID] = {
"orderID": ticketID,
"userID": msg.author.id,
"guildID": msg.guild.id,
"channelID": msg.channel.id,
"order": order,
"status": "Unclaimed",
"ticketChannelMessageID": m
};
// Write JSON information.
fsn.writeJSON("./orders.json", orderDB, {
replacer: null,
spaces: 4
}).then(() => {
// Sends an embed to the customer.
msg.channel.send("Thanks for ordering! Your order will be delivered soon, Order ID: `\`${ticketID}\``");
// Logs in console.
console.log(colors.green(`${msg.author.username} ordered "${order}" in ${msg.guild.name} (${msg.guild.id}) in ${msg.channel.name} (${msg.channel.id}).`));
}).catch((err) => {
if(err) {
msg.reply(`There was a database error! Show the following message to a developer: \`\`\`${err}\`\`\``);
console.log(colors.red(`Error in order ${ticketID}: ${err}`));
}
});
});
});
}else {
msg.reply("This server is currently blacklisted.");
}
});
});
};```
Welcome to StackOverflow! It simply means that there's no value in fields[0]. Try this:
fields: [{
name: "Order Description",
value: order || "None", // Returns None if no order
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Order Status",
value: ticketID",
}],
A better solution is to check if all the needed variables are what you expect. For example you could add this before your code:
if (!order) return msg.reply("No order found.");

Vuejs search in array of object

i have an API Laravel response such this:
{
id:1,
name: "Text",
category: {
id: 1,
name: "Text 2",
},
tags:[
{
id: 1,
name: "Tag1",
},
{
id: 2,
name: "Tag2",
},
],
},
For my front-end (with vuejs) i've created a simple computed function to filter the category, based on the user's selection of checkboxes.
checkedCategory: []
.
.
let posts = this.posts;
if (typeof this.checkedCategory !== 'undefined' && this.checkedCategory.length > 0) {
posts = posts.filter((post) => {
return this.checkedCategory.indexOf(post.category.name) > -1;})}
Everything works.Posts are filtered by the categories chosen by the user.
But, posts can also have several tags.
Is an array of objects, so i reformulated the block with an .includes (instead of .filter), but it returns an empty result.
checkedTags: []
.
.
let posts = this.posts;
if (typeof this.checkedTags !== 'undefined' && this.checkedTags.length > 0) {
posts = posts.includes((post) => {
return this.checkedTag.indexOf(post['tags']) > -1;})}
I think this should work:
let posts = this.posts;
if (typeof this.checkedTags !== 'undefined' && this.checkedTags.length > 0) {
posts = posts.filter(post => {
return post.tags.some(tag => checkedTags.includes(tag.name))
})
}
Basically it will just filter all the posts where at least one tag is in the checkedTags array. Depending on your needs you can also check if all the tags of the post are there with post.tags.every()

Categories

Resources