So let's say I have this piece of code:
const old = await Sports.findById(sportId);
And it returns the following:
{
_id: "sdsdsds",
name: "sdsdsds",
enabled: true,
markets: [
{
enabled: true,
defId: "LOOKATME",
name: "sdsdsd",
},
{
enabled: false,
defId: "dfsdfdsfs",
name: "sdsdfsdsd",
},
]
}
Now, let's say I want to update the market with the defId of "LOOKATME" so it enabled becomes false.
Would it be possible to added inside an update function such as this:
const updated = await Sports.findByIdAndUpdate(old, [LOGIC], {new: true});
How would I go about doing this so the output is this:
{
_id: "sdsdsds",
name: "sdsdsds",
enabled: true,
markets: [
{
enabled: false, // this is what changed
defId: "LOOKATME",
name: "sdsdsd",
},
{
enabled: false,
defId: "dfsdfdsfs",
name: "sdsdfsdsd",
},
]
}
const updated = await Sports.updateOne({_id: old._id, "markets.defId": "LOOKATME"}, {$set: {"markets.$.enabled": false}}, {new: true});
Related
Is there any way to list all databases on a MongoDB server via Prisma programmatically with typescript?
You can use the $runCommandRaw prisma function to list all the databases.
main.ts
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
log: ['query'],
});
async function main() {
const output = await prisma.$runCommandRaw({ listDatabases: 1 });
console.log(output);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
Here's the output:
> ts-node index.ts
{
databases: [
{ name: 'prisma', sizeOnDisk: 57344, empty: false },
{ name: 'sample_airbnb', sizeOnDisk: 55226368, empty: false },
{ name: 'sample_analytics', sizeOnDisk: 9609216, empty: false },
{ name: 'sample_geospatial', sizeOnDisk: 1437696, empty: false },
{ name: 'sample_mflix', sizeOnDisk: 56508416, empty: false },
{ name: 'sample_restaurants', sizeOnDisk: 8863744, empty: false },
{ name: 'sample_supplies', sizeOnDisk: 1191936, empty: false },
{ name: 'sample_training', sizeOnDisk: 62578688, empty: false },
{ name: 'sample_weatherdata', sizeOnDisk: 3694592, empty: false },
{ name: 'admin', sizeOnDisk: 339968, empty: false },
{ name: 'local', sizeOnDisk: 4137603072, empty: false }
],
totalSize: 4337111040,
totalSizeMb: 4136,
ok: 1
}
Please make sure that to run listDatabases command you need to be on the admin database, so your connection string should point to admin database
Example:
DATABASE_URL="mongodb+srv://username:password#cluster0.souw3.mongodb.net/admin"
I have embedded a PowerBI report. This is the Javascript with the page setup.
For some reason I don't get a vertical scrollbar in my report. When I open it in the workspace online the scrollbars work just fine. I already tried switching between different 'View' options in PowerBi but that does not seem to make a difference.
<H2>PowerBI</H2>
<p><i>User: {{username}} | AccessLevel: {{access_level}}</i></p>
<div id="reportContainer" style="height: 80vh;"></div>
<script type="text/javascript">
window.onload = function () {
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;
var embedConfiguration = {
type: 'report',
id: '{{txtembedreportid}}',
embedUrl: '{{txtreportembed}}',
tokenType: models.TokenType.Embed,
accessToken: '{{txtaccesstoken}}',
settings: {
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: models.PageSizeType.Widescreen,
}
},
panes:{
bookmarks: {
visible: false
},
fields: {
expanded: false
},
filters: {
expanded: false,
visible: false
},
pageNavigation: {
visible: true
},
selection: {
visible: true
},
syncSlicers: {
visible: true
},
visualizations: {
expanded: false
}
}
}
};
var $reportContainer = $('#reportContainer');
var report = powerbi.embed($reportContainer.get(0), embedConfiguration);
report.fullscreen();
}
</script>
Try adding the "displayOption" property with value "FitToWidth" in customLayout object, as this option will try to fit the report as per the total available size for the page and will introduce a scrollbar for the remaining part if necessary.
Also change "Widescreen" to "Custom" in pageSizeType object
After all changes, your embedConfiguration will become as following.
var embedConfiguration = {
type: 'report',
id: '{{txtembedreportid}}',
embedUrl: '{{txtreportembed}}',
tokenType: models.TokenType.Embed,
accessToken: '{{txtaccesstoken}}',
settings: {
layoutType: models.LayoutType.Custom,
customLayout: {
displayOption: models.DisplayOption.FitToWidth, // Add "FitToWidth"
pageSize: {
type: models.PageSizeType.Custom, // Change to "Custom"
}
},
panes:{
bookmarks: {
visible: false
},
fields: {
expanded: false
},
filters: {
expanded: false,
visible: false
},
pageNavigation: {
visible: true
},
selection: {
visible: true
},
syncSlicers: {
visible: true
},
visualizations: {
expanded: false
}
}
}
};
Refer docs: https://learn.microsoft.com/en-us/javascript/api/overview/powerbi/custom-layout
I have no idea how to make this,
I have a loop for product List Item, but i really don't know how to link the shop item to shop name. I have tried many method but i really don't know how to link the item to the shop.
if productList.ShopId = shopList.id then use this shopList.title
SHOP NAME = shopList.title
const getProductList = function (productItem) {
const productListRender =
$('<div>').append($('<span>', {
html: shopName() <<<< SHOP NAME
}));
$.each(data.shopList), function shopName() {
this.text(shopList.title);
};
return productListRender;
}
const $product = $('#List')
$.each(data.productList, function (index, data) {
$product.append(getProductList(data));
});
Data JS is Below:
var data = {
productList: [
{
id: "62276197-6059-4c21-9b40-c5b1d277e85d",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000001_12032019.png",
text: 'Product 001',
goldMedal: false,
newItem: true,
newShop: true,
freeDelivery: true,
ShopId: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb'
},
{
id: "59de8216-052d-4e51-9f7d-7e96642ded62",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000002_12032019.png",
text: 'Product 002',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
},
{
id: "59de8216-052d-4e51-9f7d-7e96642ded62",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000003_12032019.png",
text: 'Product 003',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
}],
shopList: [{
id: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb',
title: 'Shop 001'
},
{
id: '10eb4250-47d6-41ad-a429-f65e05836f26',
title: 'Test Shop'
}]
}
Refine shopName as:
function shopName(shopId) {
// find the right shop by comparing shopId with each `shop.id`
// uses optional chaining to prevent errors
// returns undefineds if no match is found
return shopList.filter(shop => shop.id === shopId)?.[0]?.title;
}
const shopList = [{
id: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb',
title: 'Shop 001'
},
{
id: '10eb4250-47d6-41ad-a429-f65e05836f26',
title: 'Test Shop'
}]
console.log(shopName('10eb4250-47d6-41ad-a429-f65e05836f26'));
console.log(shopName('222'));
everything seems to be in order in your data. only thing that i can see is that there was some mishap in your comparison method.
have you tried comparing them not with equal sign but rather treat them as string .
you could see this link for reference..
https://www.tutorialspoint.com/What-is-the-best-way-to-compare-two-strings-in-JavaScript
I'm currently working on an Angular application and want to iterate over an array of objects that have nested data. I want to mutate the existing array when a user clicks a checkbox changing the checked property from false to true and vise Versa. For simplicity sake, I'm only posting the array structure.
I tried
const checklistCashe = [
{
categories: [
{
title: "Administrators",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
},
{
title: "Associates",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
{subTitle: "Users", checked: false},
]
},
{
title: "Organization",
items: [
{subTitle: "Contract", checked: false},
{subTitle: "External", checked: false},
{subTitle: "Internal", checked: false},
]
},
{
title: "Products",
items: [
{subTitle: "Concept", checked: false},
{subTitle: "Demo", checked: false},
{subTitle: "Production", checked: false},
]
},
{
title: "Reporting",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
}
]
}
]
const category = "Reporting";
const subCategory = "Admin";
I want to mutate the current array based on the category and subCategory provided. So I only want the checked property to change if the title is Reporting and the subTitle is Admin.
{
title: "Reporting",
items: [
{subTitle: "Admin", checked: true},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
}
The best way with what you have would be something like:
function toggleChecked(title, subtitle) {
checklistCashe[0].categories.forEach((category) => {
if (category.title === title) {
category.items.forEach((item) => {
if (item.subTitle === subtitle) {
item.checked = !item.checked;
}
});
}
});
}
However, I feel like you might be better off formatting your checklistCashe to something more like:
const checklistCashe = {
Administrators: {
Admin: false,
Associates: false,
Hr: false
}
[...]
}
Then you can do something more like:
function toggleChecked(title, subtitle) {
checklistCashe[title][subtitle] = !checklistCashe[title][subtitle]
}
and you wouldn't have to iterate.
If you wanna keep it clean then use lodash as shown below
const checkListCache = [
{
categories: [
{
title: 'Administrators',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
],
},
{
title: 'Associates',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
{ subTitle: 'Users', checked: false },
],
},
{
title: 'Organization',
items: [
{ subTitle: 'Contract', checked: false },
{ subTitle: 'External', checked: false },
{ subTitle: 'Internal', checked: false },
],
},
{
title: 'Products',
items: [
{ subTitle: 'Concept', checked: false },
{ subTitle: 'Demo', checked: false },
{ subTitle: 'Production', checked: false },
],
},
{
title: 'Reporting',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
],
},
],
},
];
const category = 'Reporting';
const subCategory = 'Admin';
const { categories } = checkListCache[0];
const selectedCategory = _.find(categories, ['title', category]);
const selectedSubCategory = _.find(selectedCategory.items, ['subTitle', subCategory]);
selectedSubCategory.checked = !selectedSubCategory.checked;
console.log(checkListCache);
You can add safety checks as well before each loop to ensure we have values before manipulating it.
Use nested map calls:
function mutate (arr)
{
return arr.map(innerArr =>
{
return {
title: innerArr.title,
items: innerArr.items.map(item => {
return {
subTitle: item.subTitle,
checked: (innerArr.title === "Reporting" && item.subTitle === "Admin") ? false : item.checked,
};
}),
};
});
}
I am trying to update the value of an object using $ set to pass an Object into a nested array element, however the element tha is updated is the first element not the one I query. I am not sure what I am doing wrong.
Schema
const storySchema = new mongoose.Schema({
//some fields
stages: [{
//some fields
events: [{
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
body: {
type: String,
required: true,
trim: true
}
}]
}]
})
The update route in express
Story.findOneAndUpdate({ 'stages.events._id': req.params.eventId }, {
'$set': {
'stages.0.events.$': req.body.event
}
}, {
new: true,
runValidators: true
})
Following the #Veeram suggestion, I used arrayFilters in the solution.
Here is the solution.
Story.findOneAndUpdate({ 'stages.events._id': req.params.eventId }, {
'$set': {
'stages.0.events.$[event]': req.body.event
}
}, {
new: true,
runValidators: true,
arrayFilters: [{ 'event._id': mongoose.Schema.Types.ObjectId(req.params.eventId) }]
})
you can use this
Story.findOneAndUpdate({ 'stages.events._id': req.params.eventId }, {
'$set': {
'stages.$.events.$': req.body.event
}
}, {
new: true,
runValidators: true
})