CastError: Cast to date failed for value date at path - javascript

I'm trying to make a query in my database developed in Mongo, we have the schema Examen (or Exam) and we need to find all the exams between two dates.
My system can get both dates and make the Query with this form (im using Moment as well in order to get the correct format)
This is the query that I get from the website
{ "examDate": { "$gt": { "$date": "1556686800000" }, "$lt": { "$date": "1559192400000"} } }
when I run this query in Studio3T it works normally but in the website it has an error:
CastError: Cast to date failed for value "{ '$date': '1559192400000'
}" at path "examDate" for model "Examen"
I have tried to change the '$date' format using the ISO format as well, that didn't work. And is weird that the query works normally in Studio3T but it dont works like this using the Mongo db.find() function.
//this is how I make the find function for my schema
Examen.find((query), (err, info_examen) => {
if (err) return res.status(500).send({ message: `Error: ${err}` })
if (!info_examen) return res.status(404).send({ message: `there is no data` })
res.status(200).send({ info_examen })
})
I expect to get the result (info_examen) in order to make statistics with the data.

Related

Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: an array"

I have a web to check somebody's salary. Every time an icon is clicked, the data of the salary will be sent to the firebase. But it constantly gives me an error.
Err : FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: an array
My database consists of a list of people and each person has the details of their salary, in an array, such as overtime pay, meal allowance, basic salary etc.
Here is my data
data(){return{newSalary: {basicSalary:null, overtimePay:null, mealAllowance:null}}}
and here is my method
async addGaji(rowIndex){
let values = Object.values(this.newSalary);
if (values.includes(null)){
showToast({
message: "Input is missing",
color: "red"
});
console.log(this.operators[rowIndex].originalData.salary)
} else {
await db.collection('operator').doc(this.operators[rowIndex].originalData.salary).push(this.newSalary)
.then(() => {
showToast({
message: "Data has been uploaded",
color:"blue"
})
})
.catch(console.log(this.operators[rowIndex].originalData.salary));
}
}
Can somebody help me to solve this problem?
I've already use concat because I thought it can join new array to the existing array inside firebase salary data

Query MongoDB to display only one section of data

I have created a MongoDB database and have it hooked up to a MEAN stack web application I have created. I have it able to display the most recent set of data put into it rather than all of the data but now I want to take that down to display only 1 section of that data, as there are currently 50 different sections.
I am using post.find and then sorting the data to show only the most recent record from the DB but I am struggling to break it down to show only one part of that data. Current data: https://imgur.com/a/cwKTCEa.
As you can see the data is grouped by "S0" and then data follows, then there is "S1" etc... In essence what I want is for just "S0" to be displayed when queried.
exports.list = function (req, res) {
Post.find().sort({ _id: -1 }).limit(1)
.then(function (posts) {
return res.status(200).json({
status: 200,
data: posts,
message: 'Success'
})
})
.catch(function (err) {
return res.status(400).json({
status: 400,
message: err.message
});
});
}
I believe I need to add to the find query but I am not sure how to specify that I would only like to see "S0" rather than S0-S49.
Thank you
If you want to return only specific fields from query you should use Project Fields:
Post.find({}, {"s0": 1}).sort({ _id: -1 }).limit(1)
Here is the docs Project Fields

How to perform date comparisons against postgres with sequelize

I want to delete all records with dates before 20 minutes ago. Postgres (or Sequelize) is not satisfied with the bare javascript Date object I provide as the comparison value.
I'm using sequelize 4.37 on top of a postgres 9.6 database.
The column in question was declared with type: Sequelize.DATE, which research suggests is equivalent to TIMESTAMP WITH TIME ZONE: a full date and time with microsecond precision and a timezone signifier. (That is also what I see when I use the psql CLI tool to describe the table.)
So, I do this:
const Sequelize = require('sequelize')
const { SomeModel } = require('../models.js')
// calculate 20 minutes ago
async function deleteStuff() {
const deletionCutoff = new Date()
deletionCutoff.setMinutes( deletionCutoff.getMinutes() - 20 )
await SomeModel.destroy({
where: {
[ Sequelize.Op.lt ]: { dateColumn: deletionCutoff }
}
})
But I get this error:
Error: Invalid value { dateColumn: 2018-11-21T21:26:16.849Z }
The docs suggest I should be able to provide either a bare javascript Date, or an ISO8601 string, but both throw the same Invalid Value error. The only difference is that, if I pass a string, the error shows single quotes around the value:
// error when dateColumn: deletionCutoff.toISOString()
Error: Invalid value { dateColumn: '2018-11-21T21:26:16.849Z' }
Well, this is pretty embarrassing. I structured the where clause incorrectly.
// BAD CODE
await SomeModel.destroy({
where: {
[ Sequelize.Op.lt ]: {
dateColumn: deletionCutoff
}
}
})
// GOOD CODE
await SomeModel.destroy({
where: {
dateColumn: {
[ Sequelize.Op.lt ]: deletionCutoff
}
}
})
Maybe I should delete the question. Maybe not -- the error I got probably could be more helpful.

Express js with mysql update only fields that are passed

I've been trying to setup a rest API for a few days now. I've been following a great tutorial that really helped me understand a large part of how these work (sending requests, getting responses, etc). However it uses MongoDB and Mongoose. I'm using MySQL. My tables and views are a bit complicated so I decided instead of using an ORM I'd just use mysql2 package and do the querying myself. I'm stuck with trying to PATCH and PUT at the moment. Part of my front end functions by sometimes only sending 1 or 2 fields that need to be updatd (a PATCH from everything I've gathered). So I used part of the MongoDB and Mongoose tutorial to build an array of objects and pass them into connection.query. Here's my patch route:
router.patch('/:txnid', (req, res, next) => { //UPDATE fields that are passed
const txnid = req.params.txnid;
for (const field of req.body) {
fieldsToUpdate[field.name] = field.value;
}
connection.query("UPDATE QuoteToClose SET ? WHERE qb_TxnID = '" + txnid + "'", { fieldsToUpdate }, function (error, results) {
if (error) {
res.status(404).json({
message: error,
field: fieldsToUpdate
});
} else {
res.status(201).json({
"record_count" : results.length,
"error": null,
"response": results
});
}
});
});
Sometimes I will pass 1 field, sometimes I will pass 2. In this case I'm only passing 1. I build my body in POSTMAN and send this with the PATCH request:
[
{
"name": "margin",
"value": "50"
}
]
When I run this through POSTMAN I get the error:
{
"message": {
"code": "ER_BAD_FIELD_ERROR",
"errno": 1054,
"sqlState": "42S22",
"sqlMessage": "Unknown column 'fieldsToUpdate' in 'field list'"
},
"field": {
"margin": "50"
}
}
I'm not sure why though. I'm not using Mongoose unfortunately so I don't know if something is dependent on it that I'm missing. My body parser is set like this:
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
I want to dynamically build that query instead of specifying each field (it just seems cleaner this way.
Hi im using this library build dynamic queries.https://www.npmjs.com/package/flexqp
let result = await qp.executeUpdatePromise('update user set ? where user.id = ?', [user, user.id], dbconfig);
user is an object with lots of sub elements, the library will auto populate the
query to E.g update user set name = 'xxx' , address ='xxx' ..etc where user.id = 1
fieldsToUpdate is already an object. If you remove the curlies when you parameterize if you should be good to go:
connection.query("UPDATE QuoteToClose SET ? WHERE qb_TxnID = '" + txnid + "'", fieldsToUpdate,
Also, as a side note that string concatenation is a bad idea, you're just asking for a SQL Injection attack.

How to emit object using socket.io?

I have a code like, I have a problem with sending response.
socket.on('findUserMessages', (userName) => {
io.sockets.connected[socket.id].emit('Checking-message', {
type: 'ss',
text: bot,
user: 'bot'
});
var dupa = db.chat.find({ user: userName }, function(err, docs) {
userName = userName
if (err) throw err;
console.log('load old messages', docs)
})
io.emit('private message', dupa);
})
My node console output is like
[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]
I know that output is not a JSON string, how to solve that? I was trying to use .toArray() but without succes.
That might be silly question but I am stuck with it for a long time.
Convert to json your result before emitting it. Try to emit JSON.stringify(dupa).
EDIT
Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there (JSON.strigify(result) on client side on receiving the emit event).

Categories