I am using sequelize .literal function to create an aggragated field, which was not achievable in other ways. Now I want to use sequelize's built-in "where" clause to filter by values on this new field.
DB_A.findAll({
attributes: {
include: [
[
sequelize.literal(
`(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
),
"b_count",
],
]}
where:{ b_count:{[Op.gte]:10}}
})
When I do this, I get "Unknown column 'DB_A.b_count' in 'where clause'". I've also tried:
where:{[sequelize.literal("b_count")]:...}
Which works with the order property from sequelize, but not here.
Any ideas?
Ok, I figured it out. You need to use "having" instead of "where", as it would be the way to do with regular MySQL. For some reason Sequelize.having is not on the DOCS/API, and I already opened an issue at the git repo.
The above code would then be:
DB_A.findAll({
attributes: {
include: [
[
sequelize.literal(
`(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
),
"b_count",
],
]}
having:{ ["b_count"]:{[Op.gte]:10}}
})
Related
Hello i am using mongoose.
I have built this query that finds my desired project :
const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'testing#email.com'} , { 'project.$.companyName': 1 });
this returns an object from my database like this :
{
'projectName' : 'x',
'companyName' : 'x bv'
}
How can i update the company name to be 'Y bv' instead of 'x bv'.
Assuming this is your document structure,
{
"_id" : ObjectId("5f2ae5a4b1549ac0460920dd"),
"projectName" : "A",
"project" : [
{
"companyName" : "T1",
"contactPerson" : {
"work_email" : "t1#gmail.com"
}
},
{
"companyName" : "T2",
"contactPerson" : {
"work_email" : "t2#gmail.com"
}
}
]
}
Single Update updateOne()
If you know email will be unique and want to update single document then use updateOne().
first is query part to find condition, email t1#gmail.com
second is set/update part, here $ is for array because project is an array, update companyName to T1 Company
await ClientManagers.updateOne(
{ 'project.contactPerson.work_email': 't1#gmail.com' },
{
$set: { "project.$.companyName": "T1 Companmy" }
}
)
Multiple Update updateMany()
If email is not unique and want to update everywhere then use updateMany(), it will update every matching documents.
await ClientManagers.updateMany(
{ 'project.contactPerson.work_email': 't1#gmail.com' },
{
$set: { "project.$.companyName": "T1 Company" }
}
)
Not suggesting update() method to use, because its deprecated in mongoose and will give Deprecation Warnings
, this function is replaced with updateOne(), updateMany() and replaceOne() methods.
Good start. Mongo has better documentation with examples. I suggest you to refer that also.
use update
db.collection.update({companyName:'x bv'}, {"$set":{"companyName":y}})
Mongo is case sensitive. So name should match exactly.
update updates one document. To update multiple, use updateMany or multi:true option with update or findOneAndMondify for one update for find and update case.
does anybody know how to filter mongodb db.adminCommand output? Because if I run this command db.adminCommand({ "currentOp": true, "op" : "query", "planSummary": "COLLSCAN" }) I get a huge JSON output but I'm only interested in some fields ( like secs_running, op, command, $db)
Many thanks!
You can add the filters straight to the command object like the following:
var commandObj = {
"currentOp" : 1,
"waitingForLock" : true,
"$or" : [
{
"op" : {
"$in" : [
"insert",
"update",
"remove"
]
}
},
{
"command.findandmodify" : {
"$exists" : true
}
}
]
};
db.adminCommand(commandObj);
You can see some filter examples on the MongoDB docs: https://docs.mongodb.com/manual/reference/method/db.currentOp/#examples
Just re-read your question and I think you might of meant just projecting fields back from the database that you care about? if that's the case you can just execute a map on top of the current results so you only see what you care about?
db.adminCommand(commandObj).inprog.map(x => x.opid};
select reservation_datetime
from LectureReservation
Inner Join Lecture
On LectureReservation.lecture_id = Lecture.id
Where Lecture.mentor_id = 1
This is my query and I want to change it to sequelize like
if (req.params.id) {
LectureReservation
.findAll({
include: [{
model: Lecture,
where: { mentor_id: req.params.id },
}],
attributes: ['reservation_datetime'],
where: {
lecture_id: Lecture.id,
},
this.. I tried it so hard but can't find solution and my postman keep showing me
"name": "SequelizeEagerLoadingError"
this err..
plz help me to translate query to sequelize..!
Sequelize will do _outer join without required = true.
The errors you have received usually is from association problem.
Try set logging :console.log and check the raw query.
this below Sequelize work fine for me without using order, i'm wondering why i can't use order for root table as posts model? when i use this below code i get this error:
Unhandled rejection Error: 'posts' in order / group clause is not valid association
but that work fine on other models such as channelVideoContainer
models.posts.findAll({
where: {
channelId: 1
},
include: [
{
model: models.channelVideoContainer,
include: [models.fileServerSetting]
}, {
model: models.channelMusicContainer,
include: [models.fileServerSetting]
}, {
model: models.channelImageWithTextContainer,
include: [models.fileServerSetting]
}, {
model: models.channelFilesContainer,
include: [models.fileServerSetting]
},
models.channelPlainTextContainer
], order: [
[{model: models.posts}, 'id', 'DESC'],
], limit: 5
}).then(function (result) {
console.log(JSON.stringify(result));
});
You are getting this error because you are querying the posts table/model, and then sorting by a column on the posts model, however you are specifying a "joined" table in your order. This works for your other models because they are in fact joined (using the include option). Since you are querying the posts model you just need to pass in the name of the column you want to order by. See some of the ORDER examples in the documentation.
// just specify the 'id' column, 'post' is assumed because it is the queried Model
order: [['id', 'DESC']],
As a side note, you may want to specify required: false on your include'd models to perform a LEFT JOIN so that rows come back even if there are no matches in the joined table. If you know that rows will be returned (or they are actually required) then leave it as is.
{
model: models.channelFilesContainer,
include: [models.fileServerSetting],
required: false, // LEFT JOIN the channelFilesContainer model
},
I want to create an custom search using Suite Script 2.0 version with the Filter Condition as an Formula Date Field with NVAL2 Function
I'm achieving this search on the UI as Saved Searches but i want create it on the Code itself.
Search Filter Created on the UI(Saved Search):
My Code:
var mySearch = search.create({
type: 'customrecord_configuration',
columns: ['custrecord_supervisor'],
filters: [
[
[
['custrecord_from_date', 'greaterthanorequalto', fromDate], 'AND', ['Formula Date', 'lesserthanoreqaulto', NVL2({
custrecord_end_date
}, {
custrecord_end_date
}, TO_DATE('01/01/2200', 'MM/DD/YYYY'))]
]
]
]
});
Thanks in Advance.
The internal ID for a Formula (Date) column would be formuladate, and your formula value needs to be a String:
[
'formuladate', 'lesserthanoreqaulto',
"NVL2({custrecord_end_date}, {custrecord_end_date}, TO_DATE('01/01/2200', 'MM/DD/YYYY'))"
]
If you use Chrome, you can also try this Chrome Extension that lets you export UI searches directly to code.