I want to get id of affected row in update action using Sequlaize.update method.
const result = await Voucher.update(
{
used: "1",
},
{
where: {
voucher_group_id: 5,
used: "0",
},
limit: 1,
returning: true,
}
);
when I set returning to true, the result was [null, 1]. but the affected row id is other value like: 72
The returning option is only for the Postgres dialect, as specified in the Sequelize v6 Documentation for Model#update.
If you are using a Dialect like MySQL, you could load in the record you want to update via Model#findOne first and then use instance#update.
const voucher = await Voucher.findOne({
where: {
voucher_group_id: 5,
used: "0"
}
});
// voucher is potentially null at this point
voucher.update({ used: "1" });
Side note: If your used field on your Voucher model is a boolean, you can use true/false and Sequelize will automatically convert these to the tiny int equivalent values for your dialect.
Related
I am using json-server for mock-backend to retrive children form a single object.
The parent table sentinel and the child table sensor
As you can see the sensors is an array and sentinel is an object.
I have used http://localhost:3000/sentinel?_embed=sensors but the response is not what i am expecting, because I want sensors: [{id: 1}, {id: 2}, ecc]
The official documentation shows that are two ways to retrive two tables:
_embed (include children) and _expand (include parent).
How could I achive this result?
Given that sentinel is a single object in your db.json and you can't have more than one sentinel it is not clear to me how your query is different from retrieving all sensors with sentinelId=10:
/sensors?sentinelId=10
In fact if you try this API:
/sentinel/10/sensors
it will work, because json-server rewrite the url exactly to the previous query.
If for some reason you don't want to use the sentinel id directly in the query, the other option is to use json-server as a module and define a custom route with the logic you need. Here's a basic example that exposes a /sentinel/sensors API and retrieve sentinel data along with the sensors whose sentinelId equals to the current sentinel id:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
console.log('Mock server is running on port ' + 3001);
});
That would give you a response like this:
{
"id": 10,
"name": "Sentinel",
"sensors": [
{
"id": 1,
"sentinelId": 10
},
{
"id": 2,
"sentinelId": 10
}
]
}
Here's a stackblitz
In my mysql table ,i have a column of JSON type
const monthlyProgress = sequelize.define("monthlyprogress", {
.
.
.
duration: {
type: Sequelize.JSON
}
});
return monthlyProgress;
in this "duration" column i have a JSON array of objects
[{"time":"nov-2020"},{"time":"dec-2020"}]
Now i need a sequelize findall to fetch the rows where the condition will e
time = "nov-2020" of that "duration" column
i have tried i many ways but failed everyime. Below i am showing one of the ways that i found on stackoverflow. But its also a failed attepmt
Its giving me output of those rows who doesnt have time="nov-2020"
await monthlyProgress.findAll({
where: {
duration: [
fn('JSON_CONTAINS', col('duration'), cast('{"time": "nov-2020"}', 'CHAR CHARACTER SET utf8'))
]
}
})
It's another attempt thats is showing this error message UnhandledPromiseRejectionWarning: ReferenceError: JSON_CONTAINS is not defined
await monthlyProgress.findAll({
where: {
[Op.and]: db.Sequelize.literal(JSON_CONTAINS(`duration`, '{\"time\": nov-2020}')),
}
})
Situation
In a project I have this code to select data from a table. Please note, it is working, I only don't get the result I expect.
serviceSurveyQuestions.find({
query: {
survey_id: this.survey_id,
user_id: this.$store.state.auth.user.id, //TODO move this to the hook!!
//todo make satus also not equal new
$or: [
{ status_id: process.env.mfp.statusSurveyQuestionStarted },
{ status_id: process.env.mfp.statusSurveyQuestionPlanned }
],
$sort: {
survey_question_question: 1
},
$limit: 150,
$select: [
'survey_question_question',
'survey_question_at',
'survey_question_answer',
'survey_question_details',
'survey_question_source_id',
'survey_question_source_answer_id',
'survey_question_source_user_id',
'survey_question_step',
'survey_question_dep_step',
'id'
]
}
}).then(page => {
this.listSurveyQuestions = page;
});
When I see what would be in one item of listSurveyQuestion I will see this:
{
"survey_question_question": "PEN 10 Scope vaststellen",
"survey_question_at": "2017-06-23T06:46:10.038Z",
"survey_question_answer": "",
"survey_question_details": "tester done",
"survey_question_source_id": 83499707,
"survey_question_source_answer_id": 74864,
"survey_question_source_user_id": 83488216,
"survey_question_step": 10,
"survey_question_dep_step": null,
"id": 4651,
"source_user": {
"user_id": 1005
},
"status": {
"status": "Planned"
},
"language": {
"language": "Dutch"
,
"source": {
"source": "MexonInControl - Pob - Dev (local)"
},
"survey_question": [{
"answer_type_id": 1014,
"answer_en": null,
"answer_nl": null,
"answer_explanation_en": null,
"answer_explanation_nl": null,
"survey_question_next_id": 4652
} ]
}
I know the result is comming from the configuration in my get and find hook of the service being called.
Expected Result
What I expect to happen is that the data returned is only the columns defined in the $SELECT. If I leave this as is, it will work but I'm getting to much data from the database which can be seen later as a security breach. Not with this example, but with other tables it will.
** Question **
So what do I need to change to have this functioning as expected. You could adapt the return of the service, but then I can't use the same service in other situations for the columns aren't available. Or can you pass an option to the service which will result in if (parameter = view 1) then return view 1 and so on.
** Solving **
Remark 1:
So I just see the 'cause' is a bit different. The configured hooks returns more columns from the question table which are not shown. So my guess here is that if you don't configure the includes in the find query, it will pass all includes. I need to check that and if this is the case, see if there is a option to not select the 'includes' as well.
Assuming that the hook you are referring to is setting hook.params.sequelize similar to this answer you will have to check if you included properties are also set in the $select query with something like this:
// GET /my-service?include=1
function (hook) {
const include = [];
const select = hook.params.query.$select;
// Go through all properties that are added via includes
['includeProp1', 'includeProp2'].forEach(propertyName => {
// If no $select or the include property is part of the $select
if(!select || select.indexOf(propertyName) !== -1) {
include.push({ model: ModelForIncludeProp1 });
}
});
hook.params.sequelize = { include };
return Promise.resolve(hook);
}
How can I query a dynamodb2 table with an index using boto? I'm not able to piece together enough information from the documentation or unit tests for boto.
I have a local index created as:
fields.KeysOnlyIndex('NameIndex', parts=[
fields.HashKey('account_id', data_type='S'),
fields.RangeKey('name', data_type='S'),
])
And would like to lookup an item using the account_id and name.
Attempting to make the call table.query( account_id__eq=account['id'], name__eq = name ) results in the error Query condition missed key schema element id.
Note: I would also prefer to avoid using the Table class and work directly with the connection.
with Table:
table = Table('accounts')
results = table.query(index='NameIndex', account_id__eq=account['id'], name__eq=name)
or with Connection:
results = conn.query(
table_name='accounts',
index_name='NameIndex',
select='ALL_PROJECTED_ATTRIBUTES',
key_conditions={
'account_id': {
'AttributeValueList': [
{'S': account['id']},
],
'ComparisonOperator': 'EQ',
},
'name': {
'AttributeValueList': [
{'S': name},
],
'ComparisonOperator': 'EQ',
},
}
)
new to DOJO..using JsonRest to get data from database...i have given range to display 0-1000 out of 50000 ...but it is displaying full data......requirement is that when that 1000 loaded while scrolling the next request goes to server and rest of the data will display....
please help i tried a lot ......
my code
myStore = dojo.store.Cache(dojo.store.JsonRest({
target : "myip7080/GridExample/string"
}), dojo.store.Memory());
myStore.query({
start: 0,
count: 1000
}).then(function(results){
alert(results);
});
grid = new dojox.grid.DataGrid({
store : dataStore = dojo.data.ObjectStore({
objectStore : myStore
}),
structure : [ {
name : "SNO",
field : "sno",
width : "100px",
editable : true
}, {
name : "SNAME",
field : "sname",
width : "100px",
editable : true
}, {
name : "SALARY",
field : "salary",
width : "200px",
editable : true
} ]
}, "target-node-id"); // make sure you have a target HTML element with this id
grid.startup();
dojo.query("#save").onclick(function() {
dataStore.save();
});
});
dojo/store/Memory::query() takes two parameters:
An object that queries the data
An QueryOptions object containing the options for this query (optional)
You can query specific entries from your data like this:
myStore.query(
{ name: "John Doe" }
);
//returns all rows with name="John Doe"
You don't have to make a specific query. If you want all your data, just do myStore.query("");
If you want to limit the number of rows shown, you need to add a second parameter to represent your query options:
myStore.query(
{ name: "John Doe" },
{ start: 0, count: 1000 } //return 1000 results, starting at the beginning
);
See the documentation for dojo/store/memory::query().