How to get data from relation's with data stored in array's of Id - mongodb

I have a model batches which has data as
"id": {
"type": "string",
"id": true,
"defaultFn": "uuidv4"
},
"batchType": {
"type": "string",
"required": true,
"default": "COURSE"
},
"venue": {
"type": "string",
"required": true
},
and another Model say bookedBathes
"batchesId": {
"type": [
"string"
],
"required": true
},
and created a relations from batches model to bookedBatches model as
"relations": {
"bookedBatches": {
"type": "referencesMany",
"model": "bookedBatches",
"foreignKey": "batchesId",
"primaryKey": "id"
}
}
now I want all the batches with booked details that are stored as array's of Id in booked details from batch model
let reqObject = {
"where": {
"and": [{
userId: userId,
isActive: true
}]
},
"order": "createdAt DESC",
include: [
{{
relation:"bookedBatches"}}]
}
Batches.find(reqObject, (resError, resData) => {
if (resError) {
return cb(new HttpErrors.BadRequest(resError, {
expose: false
}))
}
return cb(null, resData);
})
But I am not getting any value can any one help to get the values through relation's
Thank You!

i have improved your code. Please try this
let reqObject = {
"where": {
"and": [{
userId: userId,
isActive: true
}]
},
"order": "createdAt DESC",
include: [
{
relation: "bookedBatches",
scope: { fields: ["id","batchesId"] }
}
]
}
Batches.find(reqObject, (resError, resData) => {
if (resError) {
return cb(new HttpErrors.BadRequest(resError, {
expose: false
}))
}
return cb(null, resData);
})

Related

Configure monitor query with limitation on aggeration

I am trying to configure a monitor that looks at data logged by cron jobs.
I want to trigger an alert if a job does stop to log data.
The query using SQL looks something like this:
POST _plugins/_sql/
{
"query" : "SELECT instance, job-id, count(*), max(#timestamp) as newest FROM job-statistics-* where #timestamp > '2022-09-28 00:00:00.000' group BY job-id, instance HAVING newest < '2022-09-28 08:45:00.000'"
}
Using exlplain I converted this to a JSON Query and made the timestamp dynamic:
{
"from": 0,
"size": 0,
"timeout": "1m",
"query": {
"range": {
"#timestamp": {
"from": "now-1h",
"to": null,
"include_lower": false,
"include_upper": true,
"boost": 1
}
}
},
"sort": [
{
"_doc": {
"order": "asc"
}
}
],
"aggregations": {
"composite_buckets": {
"composite": {
"size": 1000,
"sources": [
{
"job-id": {
"terms": {
"field": "job-id.keyword",
"missing_bucket": true,
"missing_order": "first",
"order": "asc"
}
}
},
{
"instance": {
"terms": {
"field": "instance.keyword",
"missing_bucket": true,
"missing_order": "first",
"order": "asc"
}
}
}
]
},
"aggregations": {
"count(*)": {
"value_count": {
"field": "_index"
}
},
"max(#timestamp)": {
"max": {
"field": "#timestamp"
}
}
}
}
}
}
From this query, the limitation on the aggeration max(#timestmap) is missing.
In the explain response it is here:
"name": "FilterOperator",
"description": {
"conditions": """<(max(#timestamp), cast_to_timestamp("2022-09-28 08:45:00.000"))"""
},
Ideally, this should be max(#timestmap) < now-30m
My question:
How can I integrate this into the query or the monitor?
Is there another way to do this?
Thanks a lot
Marius

Open API 3.0 parameter dependencies: required parameters if type is "one of" (with shared parameters)

I'm creating an openapi.json (version 3.0.3) schema and I'm modelling a post request. The body can look like this:
{
type: "A",
aParam: "string",
sharedParam1: "string",
sharedParam2: "integer",
sharedParam3: "string"
}
where type is one of A or B. If the type is A, the parameter aParam is required if the type is B aParam must be left out. Basically, the other way the request can look is:
{
type: "B",
sharedParam1: "string",
sharedParam2: "integer",
sharedParam3: "string"
}
How can I model this?
Here is what I tried:
{
"requestBody": {
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["A"]
},
"aParam": {
"type": "string"
},
"sharedParam1": {
"type": "string"
},
"sharedParam2": {
"type": "string"
},
"sharedParam3": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["B"]
},
"sharedParam1": {
"type": "string"
},
"sharedParam2": {
"type": "string"
},
"sharedParam3": {
"type": "string"
}
}
}
]
}
}
}
}
}
Basically, I "overloaded" the request body by using oneOf but that has a lot of duplication.
You may extract the shared properties to a base schema. It won't make the definition much less verbose but at least will remove duplicated properties definitions making them more maintainable:
"components": {
"schemas": {
"baseRequestBody": {
"type": "object",
"required": [
"type",
"sharedParam1",
"sharedParam2",
"sharedParam3"
],
"properties": {
"type": {
"type": "string",
"enum": [
"A",
"B"
]
},
"sharedParam1": {
"type": "string"
},
"sharedParam2": {
"type": "integer"
},
"sharedParam3": {
"type": "string"
}
}
},
"requestBodyA": {
"allOf": [
{
"$ref": "#/components/schemas/baseRequestBody"
},
{
"type": "object",
"required": [
"aParam"
],
"properties": {
"aParam": {
"type": "string"
}
}
}
]
},
"requestBodyB": {
"allOf": [
{
"$ref": "#/components/schemas/baseRequestBody"
}
]
}
}
}
Additionally, you might want to use Discriminator which can be used by some tools like code generators:
"requestBody": {
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/requestBodyA"
},
{
"$ref": "#/components/schemas/requestBodyB"
}
],
"discriminator": {
"propertyName": "type",
"mapping": {
"A": "#/components/schemas/requestBodyA",
"B": "#/components/schemas/requestBodyB"
}
}
}
}
}
}

How to fix "Can't use $set" error on Mongoose

I'm using mongoose with the given schema:
const StockSchema = new mongoose.Schema(
{
"materialDefinition_id": {
"type": "ObjectId",
"ref": "MaterialDefinition",
"required": true
},
"quantity": {
"type": "Number",
"required": true
},
"committedOrder_id": {
"type": "ObjectId",
"ref": "Order"
},
"committedOrderItemIndex": {
"type": "Number"
},
"detachedOrder_id": {
"type": "ObjectId",
"ref": "Order"
},
"detachedOrderItemIndex": {
"type": "Number"
},
"deletedAt": {
"type": "Number"
},
"createdAt": {
"type": "Number"
},
"updatedAt": {
"type": "Number"
}
});
I'm getting error in the following transaction:
try {
await StockModel.update(
{
$or: [
{ committedOrder_id: purchaseOrder._id },
{ detachedOrder_id: purchaseOrder._id }
]
},
{
$set: {
committedOrder_id: null,
committedOrderItemIndex: null,
detachedOrder_id: null,
detachedOrderItemIndex: null
}
}
);
} catch (err) {
console.log("Error updating stock!");
console.log(err);
}
Error:
Error updating stock!
Error: Can't use $set
at ObjectId.SchemaType.castForQuery (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/schematype.js:1368:13)
at ObjectId.SchemaType.castForQueryWrapper (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/schematype.js:1347:17)
at cast (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/cast.js:288:39)
at model.Query.Query.cast (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/query.js:4644:12)
at model.Query.Query._castConditions (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/query.js:1842:10)
at model.Query.<anonymous> (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/query.js:2097:8)
at model.Query._wrappedThunk [as _findOne] (/Users/workspace/dev/app/dev/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at /Users/workspace/dev/app/dev/node_modules/kareem/index.js:369:33
at processTicksAndRejections (internal/process/task_queues.js:75:11)
Any ideas on how to fix it?
From the documentation, update is executed on a document object, see document.prototype.update
You can try this instead:
await StockModel.findOneAndUpdate({
$where: { $or: [{ committedOrder_id: purchaseOrder._id }, { detachedOrder_id: purchaseOrder._id }] },
$set: {
committedOrder_id: null,
committedOrderItemIndex: null,
detachedOrder_id: null,
detachedOrderItemIndex: null
}
});

How do return the count of a particular field in psql db

I have a database tables with the relationships as below.
Cagetory ---> CategorItems //One to many(CategoryItem has categoryId colum)
CatgeoryItems ---> Post // One to many(Post has categoryItemId).
I want to count the total number of records in Post groupBy the categoryItemId also returning along the categoryItem name, and the categoryName. I want columns like returned
CategoryName, item, totalInPostTable
I am using sequelize rdb mapper. When i use the query below
models.Post.findAll({
include: [{
model: models.CategoryItem,
attributes: ['item'],
required: true,
include: [{
model: models.Category,
attributes: ['name'],
required: true,
group: ["name"]
}]
}],
attributes: ['categoryItemId'],
})
It returns the record below
{
"categoryItemId": 1,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 1,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 1,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 1,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 1,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 2,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
},
{
"categoryItemId": 4,
"CategoryItem": {
"item": "xxxxxx",
"Category": {
"name": "xxxxxx"
}
}
}
However,it failed and return null without error as soon as i groupBy the categpryItem id like below.
models.Post.findAll({
include: [{
model: models.CategoryItem,
attributes: ['item', [sequelize.fn('COUNT', sequelize.col('id')), 'no_category']],
required: true,
include: [{
model: models.Category,
attributes: ['name'],
required: true,
}]
}],
attributes: ['categoryItemId'],
group: ["categoryItemId"]
})
Pls what am i doing wrong ? ANy help would be appreciated.

MVVM - Bind JSON Child Elements To Kendo UI Controls

i want to bind child nodes to two different kendo ui controls , but my Kendo Data source fetches the data from service in single call ,
var viewModel = kendo.observable {
dataSource : new kendo.data.DataSource({
transport: {
read: {
url: '/data/auras',
dataType: "json",
type: 'GET',
}
},
schema: {
/////////
},
});
}
My JSON response result looks like this
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
},
{
"id": "5006",
"type": "Chocolate with Sprinkles"
},
{
"id": "5003",
"type": "Chocolate"
},
{
"id": "5004",
"type": "Maple"
}
]
}
]
Here I have to bind batter ( is child Element) to One Gridview && topping ( is child Element) to another Gridview ,
You could use schema.parse to split your JSON result into two lists. Something like:
var batters = new kendo.data.DataSource({
data: []
});
var toppings = new kendo.data.DataSource({
data: []
});
var allData = new kendo.data.DataSource({
transport: {
read: {
url: '/data/auras',
dataType: "json",
type: 'GET',
}
},
schema: {
parse: function (data) {
batters.data(data[0].batters.batter);
toppings.data(data[0].toppings);
return data;
}
},
});
allData.fetch();
var viewModel = kendo.observable({
batters: batters,
toppings: toppings
});