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
}
);
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?
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
I am getting this error only on update().
collection.update({ Id: parseInt(orderId) }, { $set: { status: updatedStatus } })
(function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
console.log('updated successfully');
}
and my mongoldb version is "mongodb": "^3.0.2".
I am trying to use a bulk delete on the results of a mongoose aggregate query.
var bulk = Collection.collection.initializeUnorderedBulkOp();
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec();
cursor.each(function(error, doc){
if(doc){
console.log(doc);
bulk.find({_id : doc._id}).removeOne();
}
});
if(bulk.length > 0) {
bulk.execute(function(error){
if(error){
console.error(error);
callback(error);
}else{
console.log(bulk.length + " documents deleted");
callback(null);
}
});
} else {
console.log("no documents to delete");
callback(null);
}
This results in the "no documents to delete" being printed before the results of the aggregate in the each loop. Normally I would expect there to be a callback function for a database operation. I have tried adding a callback function to the params of exec, but the function never gets hit:
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec(function(error, result){
console.log(error);
console.log(result);
callback();
});
Listen to the data and end events on the cursor:
cursor.on( 'data', function( data ) {
bulk.find( { "_id" : data._id } ).removeOne();
});
cursor.on( 'end', function() {
if ( bulk.length === 0 ) {
callback();
} else {
bulk.execute(function (error) {
if (error) {
callback(error);
} else {
callback();
}
});
}
});
What version of Mongoose? There's an issue on github that might be relevant. So maybe try:
var stream = Model
.aggregate(pipeline)
.cursor({ batchSize: 1000 })
.exec().stream();
stream.on('data', function(doc) {
// ...
});
I want to get all stream data with thread value but not including null. On my mongodb console it works with $ne but on my query sails model it always returns undefined?
Example query:
Stream.findOne({thread: {$ne: null } }, function(err, st){
if(err) return err;
console.log("st", st);
});
How can I resolve this?
Use the .native() method:
Stream.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({
"thread": { "$ne": null }
}).toArray(function(err, st) {
if (err) return res.serverError(err);
console.log("st", st);
return res.ok(st);
});
});
Or the .where() method:
var myQuery = Stream.find();
myQuery.where({'thread':{ '$ne': null}});
myQuery.exec(function callBack(err, results){
console.log(results)
});