So I am trying to find all documents in a database between 'X' and 'X' dates and then order those by userID. This is what I have so far:
await Expense.find(
{'date' :{'$gte': new Date(startDate), '$lte': new Date(endDate)}}),{sort: {_id: 1}}.exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray);
But it keeps giving me "TypeError: {(intermediate value)}.exec is not a function"
For added clarification I am trying to write this in mongoose:
"SELECT employeeName, SUM(amount)
FROM reimbursements
WHERE d8 BETWEEN '$startDate' AND '$endDate'
GROUP BY employeeName
ORDER BY employeeName;";
What am I doing wrong? Thank you in advance :D
Your query has few syntax issues, Please try this :
Update :
Below old code will work, but it would be better if you try this way :
try {
let data = await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 })
/** .find() will not return null, it will either return [] or [with matched docs] */
if (data.length) { // checks data != []
console.log(data)
} else { // data == []
console.log('Empty - no docs found')
}
} catch (error) {
console.log('Error Fetching Model');
console.log(error);
}
Old :
await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 }).exec(function (err, data) {
/** sort is not an option for .find() not like aggregate, it has to be on cursor which is result of .find() & .exec() should be at end which is either .find() or .sort() */
if (err) {
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray)
})
Sample : mongooseModel.find().sort().exec()
Ref : cursor.sort
Related
I've got the next data in the MongoDB:
{
...
name: Alex,
createdAt: {"$date":"2021-03-09T20:01:57.488Z"},
...
}
And I try to implement the range date query like this:
MongoClient.connect(url, (err, db) => {
if (err) {
return reject(err);
}
const dbo = db.db('dbname');
dbo.collection('users').find({
createdAt: {
$gte: new Date(dateFrom).toISOString(),
$lt: new Date(dateTo).toISOString()
}
}).toArray(
(err, res) => {
if (err) { return reject(err); }
db.close();
return resolve(res);
});
});
And always have zero-result without errors..
How coud I do the right query?
I am using Express/Ejs/Node/Mongodb
I have multiple models Im querying through and three different data sets to do stuff with.
I need to have a function that calculates the average pain level on symptoms & counts the bodyparts most logged.
I don't know how to simplify my route below and attach these functions to them and send them back to the front end to do something with.
Also any good reads on this particular problem.
My route looks like this
app.get('/dashboard', isLoggedIn, (req, res) =>{
let thirtyDays = moment().subtract(30, 'd').format('YYYY-MM-DD')
SymptomModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} }, function(error, results){
if(error){
console.log('Error: ', error)
} else {
console.log('Found all symptoms from past 30da: ', results)
}
})
TreatmentModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} }, function(error, results){
if(error){
console.log('Error: ', error)
} else {
console.log('Found all Treatments from past 30da:', results)
}
})
DoctorModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} }, function(error, results){
if(error){
console.log('Error: ', error)
} else {
console.log('Found all Doctors from past 30da: ', results)
}
})
res.render('dashboard.ejs', {
user: req.user.firstName,
data: `I would be for the last 30 days from ${now}`,
test: "I need this to be the data"
})
});
So I was able to get multiple data sets with the following code after researching and trying more.
I wanted to post this as a response to my question in case anyone else came upon it.
If you have and better suggestions on how to do this I am open to feedback.
app.get('/dashboard', isLoggedIn, async (req, res) =>{
let thirtyDays = moment().subtract(30, 'd').format('YYYY-MM-DD')
const doctorData = await DoctorModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} })
const treatmentData = await TreatmentModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} })
//const symptomData = await SymptomModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} })
SymptomModel.find({postedBy : req.user._id, created: {$gte: `${thirtyDays}`} })
.then(symptomData => {
res.render('dashboard.ejs', {
doctor: doctorData,
symptom: symptomData,
treatment: treatmentData,
user: req.user.firstName
});
})
});//closes route //req res function
I try to query MongoDB inside nodejs to get data for _id x I use
async function getTestData(id){
return new Promise((resolve, reject) => {
MongoClient.connect(uri, { useNewUrlParser: true, keepAlive: 1 }, function(err, client) {
const dbo = client.db("test");
var query = { _id: id };
dbo
.collection("smscripts")
.find(query)
.project({ 'data' : 1})
.toArray(function(err, items) {
err
? reject(err)
: resolve(items);
});
});
});
}
Query is
{ _id: '5dada7dfdca94dbaf65d9547' }
But I always get back an empty array. Anybody can help me out why the array is always empty? By the way, err is null. The id definitely exists.
in mongo db _id are prefix with ObjectId
so you need value first try this
id = ObjectId("507c7f79bcf86cd7994f6c0e")
and then compare it to ID.
hope it helps
First You need to import..
import { ObjectId } from "bson"
Then in Your code " var query = { _id: id }; " replace it with this..
var query = { '_id' : ObjectId(id) }
Then, in your code you are using .toArray() method. this would takes more time to
convert result to array. so you need to use await keyword before moving on.
Using Async-Await pattern this is very simple ..
const client = await MongoClient.connect(uri, { useNewUrlParser: true, keepAlive: 1 })
.catch(err => { console.log(err); });
if (!client) return;
try {
const dbo = client.db('test');
let collection = dbo.collection('smscripts');
let query = { '_id' : ObjectId(id) };
let projection = { 'data' : 1 } ;
let cursor = await collection.find(query, projection).toArray();
console.log(cursor);
return cursor;
} catch (err) {
console.log(err);
} finally {
client.close();
}
hope this works for you.
I'am trying to add to date fields and some user info fields to a document, when inserting it into mongo (using db.collection.save).
Here is my code:
collection.save(
{document},
{
$set: {
"document.createdBy": "2",
"document.updatedBy": "2",
"document.created": new Date(),
"document.updated": new Date()
}
},
(err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
}else{
res.status(200).json({ status: 'ok' })
//return next();
}
});
Mongo only inserts the document and none if the fields in the $set. Any ideas to what I'am doing wrong?
There is no argument for the $set operator in .save() query in mongodb
So instead try to append the object before the query
document.createdBy = "2",
document.updatedBy = "2",
document.created = new Date(),
document.updated = new Date()
collection.save(document, (err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
} else {
res.status(200).json({ status: 'ok' })
//return next();
}
})
I have some trouble making queries inside a callback running in Meteor Mongo. Anyone is seeing what I am doing wrong here? Thanks!
var houseInserted = Houses.insert({
building_number: address.building_number,
},function(error, results){
if(error) throw error;
console.log(results); // runs
Meteor.users.update( { _id: this.userId }, // Does not execute
{ $set: { 'profile.housed': true , 'profile.address' : results }
}, function(err, doc){
if (err) throw err;
console.log(results); // runs
console.log(doc);
});
console.log(results); // runs
}
);