Unable to query data between two dates in MongoDB - node.js

db.test.find({"date":{$gte:"2017-04-11",$lt:"2017-04-13"}},function(err,doc){
console.log("date function called");
res.json(doc);
console.log(doc);
});
code works fine in mongodb and output,but in nodejs the output is empty array.

Collections can be queried with find. The result for the query is actually a cursor object. This can be used directly or converted to an array. Making queries with find()
cursor.toArray(function(err, docs){}) converts the cursor object into an array of all the matching records. Probably the most convenient way to retrieve results but be careful with large datasets as every record is loaded into memory. toArray
The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date. Return Date
var collection = db.collection('test');
collection.find({ "date": { $gte: new Date("2017-04-11"), $lt: new Date("2017-04-13") } })
.toArray(function (err, doc) {
console.log("date function called");
if (err) {
console.error(err);
} else {
console.log(doc);
res.json(doc);
}
});

Related

How can I filter arrays in mongodb using mongoose?

I have created database with two collections. Each of these collections connected with relations.
Here I want to pass one item _id and check whether it passed to other collection as foreign key. If it's passed, I want to filter all items which consist as _id. How can I do that. Here my mongoose query and screenshot of db. Thank you
route.get("/:id",(req,res)=>{
Vehicles.find({
categories: [req.params.id]
}, (err, data)=>{
if(err){
console.log(err);
}else{
console.log(data);
}
});
PS: For an example I want to get all vehicles which have category id "60c58c2dcf82de0780051378" inside categories array.
Following the mongo document, you can query for all documents where categories is an array that contains the objectId req.params.id as one of its elements.
Vehicles.find({
categories: req.params.id,
}, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});

How to make two successives synchronous queries on collections in MongoDB?

I am wondering how I can make two successives or synhcronous access to two different collections in a MongoDB database. I need to take a parameter in a first collection to use it as a parameter of .find() method in the second query. Here is my code:
MongoClient.connect(url, function(err, db) {
db.collection('questions').find( { "status": "active" } ).toArray(
function(err, item) {
var fb_id = item[0]._id;
console.log(fb_id);
db.close();
MongoClient.connect(url, function(err, db) {
var cursorC = db.collection('comments').find({questionId : fb_id }).toArray(
function(err, items) {
console.log(items);
}
);
db.close();
});
});
});
I tried unsuccessfully to chain the two connection to the database, however the second query states an undefined result.
When using both db.collection().find() function at the saeme level, in the MongoClient.connect() function I suppose both are executed asynchronously and it ends with another undefined result for the second function whose result depends on the first.
Do you have any idea to proceed using the MongoDB NodeJS driver I am using?
Thanks

Return count before limit and skip applied with mongoose

I have a schema defined in mongoose. When I want to retrieve all the items I call
Item
.find()
.limit(limit)
.skip(skip)
.exec(function (err, Items) {
if(err) { return handleError(res, err); }
return res.json(200, Items);
});
In future I want perform some filtering and then count the number of results. How can I include the number of results in the response before limit and skip applied?
I tried including count() after find, but had no luck making it working. What am I missing?
I believe two queries are necessary, you can execute them in parallel:
var Promise = require('bluebird');
Promise.all([
Item.find().limit(limit).skip(skip).exec(),
Item.count().exec()
]).spread(function(items, count) {
res.json(200, { items: items, count: count });
}, function(err) {
handleError(res, err);
});
Note that I've adapted the JSON response format in order to fit in a new property containing the count -- I've changed the response from an array to { items: Array, count: Number }.
Calling .exec() without passing a callback returns a Mongoose Promise. In the example above, I'm using Bluebird (npm install bluebird) to manage the asynchronous flow, but you could use any other library of your choice as well.

How to save a modified object in mongodb using Node.JS Driver

I want to find, modify and afterwards save an object in MongoDB. It looks like that:
var message = req.body;
db.collection('user', function(err, collection) {
collection.findOne({'facebook_id':req.params.facebook_id}, function(err, item) {
if(item) {
item.messages.push({'value': message.value, 'date': message.date});
//save Object
}
});
});
How can I now save the changes I made to the database?
Or should I instead use .update()? The problem here is, that I don't want to swap the whole object, but much more insert something into an array of that object.
Thanks & Best,
Marc
collection.update({'facebook_id':req.params.facebook_id},
{$push: { messages: {'value': message.value, 'date': message.date} } }, function(err) {
});
Use the $push operator to add a value to an array directly in the database.
http://docs.mongodb.org/manual/reference/operator/update/push/
Note that this is much more efficient than updating the entire object, especially for large objects.
db.collection.update ({'facebook_id':req.params.facebook_id}, item, function (err) {
if (err) return next (err);
});

mongoosejs query fails when filtering using a string of keys as selector

I was attempting to query docs from a mongodb and have the system return only a few fields from the documents matching the query. I first tried the syntax listed below for the first query and it failed to return i.e. the callback was never called.
I then experimented some more with alternative syntax and was able get results from the second query listed below. I'd like to understand why the first query didn't work - have I misinterpreted the syntax?
this is mongoose 3.6.8 and mongo 2.4
TIA
First query
query.find({
category:{
$in: categoryArray
}
,expiration:{$gte: new Date()}
,place:queryVal.destination
}
,'_id expiration url'
,function (err, docs) {
if (err) {
console.log(err);
} else {
console.log('queryJoin returned ' + docs.length + 'entries');
}
}
);
Second query
query.find({
category:{$in: categoryArray}
,expiration:{$gte: new Date()}
,place:queryVal.destination
})
.select({_id:1, expiration:1, url:1})
.exec(function(err, docs) {
console.log('queryJoin returns');
if (err) {
console.log(err);
} else {
console.log('queryJoin returned ' + docs.length + 'entries');
}
});
Your first attempt used Model.find syntax but you were trying to use it with Query#find which doesn't support a fields parameter. As such, Mongoose interpreted your field selection string as a callback which is why your actual callback didn't get called.

Resources