mongodb,meteor , Finding date within date range


Finding date within date range

Question:

Tag: mongodb,meteor

I am trying to find all documents with date field within date range as shown below in my Meteor app, but for some reason it is always returning empty records, can someone please tell me what I might be doing wrong / missing here? Thanks

Sample document:

_id: "tMSfNq9JR85XDaQe5"customerid: "QDGvBQhS6vYgZtnRr"date: Sun Dec 07 2014 19:50:21 GMT+0800 (HKT)description: "Test"

Tried using queries from Chrome console as follows:

Custlog.find({date: {$gt: new Date(2014, 12, 1) , $lt: new Date(2014, 12, 10) }}).fetch()

Custlog.find({date: {$gt: new Date(01/12/2014) , $lt: new Date(10/12/2014) }}).fetch()

Answer:

In their infinite wisdom, the implementors of the JavaScript Date Object made the month field zero indexed. So, January 1 is new Date(2014, 0, 1) and December 1 is new Date(2014, 11, 1). What you have Date(2014, 12, 1) is actually January 1, 2015.

Similarly, new Date(01/12/2014) is equivalent to dividing 1 by 12 and then dividing that by 2014 and then sending that as a number to the date object which is zero so it should give you the Unix Epoc, which in your time zone (GMT+08) is January 1, 1970.


Related:


Meteor/MongoDB limiting the result


mongodb,meteor
I am trying to find all documents and publish at most 5 from the results. Following this section of the MongoDB doc, I am trying to do this: Meteor.publish('teams', function () { return Teams.find().limit(5); }); Yet, in the server console, I get an exception: Exception from sub teams id Pm6jKL8Sv3FSDSTfM...

paging subdocument in mongodb subdocument


mongodb,mongodb-query
I want to paging my data in Mongodb. I use slice operator but can not paging my data. I wish to bring my row but can not paging in this row. I want to return only 2 rows of data source. How can resolve it My Query : db.getCollection('forms').find({ "_id":...

Do you get the same performance using index prefixes?


performance,mongodb,indexing
Say I have a collection containing documents like the one below: { _id: ObjectId(), myValue: 123, otherValue: 456 } I then create like below: {myValue: 1, otherValue: 1} If I execute the following query: db.myCollection.find({myValue: 123}) will I get the same performance with my index as I would if I...

AngularJS factory dependencies


javascript,html,angularjs,mongodb
I'm using AngularJS to extract information stored in mongodb. I'm trying to use a factory to retrieve that information using $http . I read so much information about how to do it, and no one works for me. Also I'm using node + express, the routes works fine. The problem...

How to use a variable as an Object Key [MongoDB] [duplicate]


node.js,mongodb
This question already has an answer here: How to use a variable as a field name in mongodb-native findOne()? 1 answer I'm trying to use variable name given to me by my function, but its actually setting the object key equal to 'name' function addlist(name, item, id){ // Add...

XMLHttpRequest to Restivus API


javascript,meteor,xmlhttprequest,cross-domain,cors
I have got a problem when sending a cross domain XMLHttpRequest to a Restivus API. Here my code for the client side script: var xhrurl = 'http://example.com:3000/api/test'; var xhr = createCORSRequest('POST', xhrurl); xhr.withCredentials = true; xhr.setRequestHeader("Content-type","application/json"); xhr.setRequestHeader("X-User-Id",object.apiUser); xhr.setRequestHeader("X-Auth-Token",object.apiKey); xhr.send(); Here the function createCORSRequest function createCORSRequest(method, url) { var xhr =...

Meteor - Multiple data contexts with Iron Router


meteor,iron-router
I just started using Meteor and Iron Router. Here I'm trying to use two data contexts but appearantly I'm doing it wrong. I've googled it but it doesn't seem this is a very common problem, but I guess it got to be possible to pass on two or more data...

Async await usage for MongoDB repository


c#,mongodb,asynchronous,parallel-processing,async-await
I have a MongoDB repository class as you see below: public class MongoDbRepository<TEntity> : IRepository<TEntity> where TEntity : EntityBase { private IMongoClient client; private IMongoDatabase database; private IMongoCollection<TEntity> collection; public MongoDbRepository() { client = new MongoClient(); database = client.GetDatabase("Test"); collection = database.GetCollection<TEntity>(typeof(TEntity).Name); } public async Task Insert(TEntity entity) { if...

Are the changes done by db command in MongoDB permanent and how?


mongodb,mongodb-query
Are the changes done using the shell in mongodb permanent ? And how MongoDb detects the config file? I am stuck in setting Slow query logs in MongoDb. We have a command db.setProfilingLevel() to set profiling level. But how can we set profiling for all databases and how to set...

How could I get the matched nested items in array


mongodb
How could I get the matched nested items in array I want to return the matched items in nested array. For example, I want to filter out the records that contain "A428 ","A429 " in their items How could I get it ? Query pipeline_work = [ { '$match': 'records.items':...

push item in sub document


mongodb,mongodb-query
I have simple collection. I want to push item in question, but it gives an exception.How can I resolve it ? /* 1 */ my collection data { "_id" : ObjectId("557e8c93a6df1a22041e0879"), "QuestionCount" : 2.0000000000000000, "Questions" : [ { "_id" : ObjectId("557e8c9ba6df1a22041e087a"), "DataSource" : [], "DataSourceItemCount" : NumberLong(0) }, { "_id"...

Meteor - Requests randomly failing


meteor,request-cancelling
I have this weird problem where some requests fails randomly. I have no idea what is causing this behavior. Sometimes it is images not loading and sometimes it is ajax request (cfs/severtime or algolia-search) and some other times everything is fine. It also happen in local and online. Here are...

Meteor: onRendered doesn't get fired again after second render iron-route


javascript,meteor,iron-router
I have an iron-router route: Router.route('/profiel/bewerken', { subscriptions: function () { return Meteor.subscribe('currentUser'); }, action: function () { if (this.ready()) this.render('profielBewerken', { to: 'container', data: function () { return Meteor.user(); } }); else this.render('profielBewerken', { to: 'container', data: { loading: true } }); } }); It waits until the subscription...

Meteor: Passing Session values from client to server


javascript,node.js,session,meteor
I am using the following code on the client side to set the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); console.log(clientid + UserSession.get("songsearcher")); I am using the following pacakge: Meteor-User-session, which will explain the use of UserSession in place of Session. Now, this works fine. But...

What are some patterns I can look at for database implementations in JavaScript?


javascript,node.js,mongodb
I'm fairly new to JavaScript, and I'm busy playing around with a node test app and MongoDB. I'm at a point where I'd like to start with the db side of the app, but I'm not sure what patterns are most commonly used in such a stack, and more importantly,...

Query not working - MongoDB


mongodb
Given this kind of documents: "_id" : ObjectId("5461c8f0426f727f16010000"), "f" : [ { "t" : "ry", "v" : 1972 }, { "t" : "g", "v" : [ "Crime", "Drama" ] }, { "t" : "ml", "v" : "English" }, { "t" : "k", "v" : "movie" }, { "t" : "ai",...

Query with filter builder on nested array using MongoDB C# driver


c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
Consider the following object structure stored as documents: public class Foo { public string Id { get; set; } public ICollection<FooBar> Bars { get; set; } // ... } public class FooBar { public string BarId { get; set; } // ... } Using a LINQ-style query with the driver...

Meteor Iron Router not loading template


javascript,meteor,iron-router
I am trying to load templates using iron router and none of the templates for the routes load. The url will change when the items are clicked but the current page never changes. Lib/router.js - Router.configure({ // we use the appBody template to define the layout for the entire app...

How to overwrite object Id's in Mongo db while creating an App in Sails


mongodb,sails-mongo
I am new to Sails and Mongo Db. Currently I am trying to implement a CRUD Function using Sails where I want to save user details in Mongo db.In the model I have the following attributes "id":{ type:'Integer', min:100, autoincrement:true }, attributes: { name:{ type:'String', required:true, unique:true }, email_id:{ type:'EMAIL',...

How to add new items to an array in MongoDB


arrays,node.js,mongodb
I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that...

CKeditor outputs Html. How to format it for displaying properly, not just lame html?


javascript,html,css,meteor,ckeditor
I am using CKeditor, and this is my code: ...othercode.. <div class="input-field col s12"> <textarea id="textarea1" class="materialize-textarea"></textarea> <label for="textarea1">Body of the Post</label> </div> <input type="submit" name="Submit" id="sub"> </form> </div> </div> </div> {{else}} <div>You are not logged in.</div> {{/if}} <script> CKEDITOR.replace('textarea1'); </script> In Javascript, I use the same id to extract...

MongoDB Java Driver 3.0 MapReduce


mongodb,mongodb-java
This is the code I'm using to run map reduce on sourceCollectionName and to get the output to targetCollectionName. But the targetCollectionName is never created. new MongoClient("localhost").getDatabase(dbName).getCollection(sourceCollectionName) .mapReduce(map, reduce) .action(MapReduceAction.REPLACE) .databaseName(dbName) .collectionName(targetCollectionName) .sharded(false); Although I'm able to get output as MapReduceIterable and when I iterate this the result is dumped...

How to get node.js to connect to mongolab using mongoose


database,node.js,mongodb,mongoose,mongolab
I've been trying to use mongoose (module for node.js and mongodb). And tried to get a connection with mongolab up and running. I tried the following at the top of my app.js file, but I couldn't seem to enter the db.on function. global.mongoose = require('mongoose'); var uri = 'mongodb://username:password#####@ds.mongolab.com:#####/db'; global.db...

How to add a subdocument in a mongoose schema


javascript,node.js,mongodb,mongoose
I am trying to create a subdocument in a mongoose schema from node.js/Express. I have two schemas: Member and Address Member.js // app/models/member.js // load mongoose since we need it to define a model var mongoose = require('mongoose'), Schema = mongoose.Schema var Address = require('./address'); var MemberSchema = Schema({ FName...

Insert data in collection at Meteor's startup


javascript,json,meteor,data,startup
I would like to insert data at Meteor's startup. (And after from a JSON file) At startup, I create a new account and I would like to insert data and link it to this account once this one created. This is the code that creates the new account at startup:...

Creating index while updating the documents


mongodb,indexing
I have a collection I am updating adding a new field. The document looks like: {"A": "P145", "B":"adf", "C":[{"df":"14", "color":"blue"},{"df":17}], "_id":ObjectID(....), "Synonyms":{"Synonym1": "value1", "Synonym2": ["value1", "value2"]}} In the update I am adding new elements to C I want to create a index on the field A and B. A and...

mongodb populate method not working


node.js,mongodb,model,populate,auto-populate
Here is my code for models var postSchema = new mongoose.Schema({ created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User" created_at: {type: Date, default: Date.now}, text: String }); var userSchema = new mongoose.Schema({ username: String, password: String, //hash created from password created_at: {type: Date, default:...

Is there a built-in function to get all unique values in an array field, across all records?


arrays,node.js,mongodb,mongoose,schema
My schema looks like this: var ArticleSchema = new Schema({ ... category: [{ type: String, default: ['general'] }], ... }); I want to parse through all records and find all unique values for this field across all records. This will be sent to the front-end via being called by service...

Creating meteor autoform w/ array of radio buttons


meteor,meteor-autoform
I'd like to build an autoform in meteor that presents user with a twelve radio buttons and records an entry for each of the 12 buttons. I can get the form working easily enough if I create 12 different buttons—see below, but I'm wondering if it is possible to create...

Inserting a variable in MongoDB specifying _id field


python,mongodb,pymongo
I want to insert a variable, say, a = {1:2,3:4} into my database with a particular id "56". It is very clear from the docs that I can do the following: db.testcol.insert({"_id": "56", 1:2, 3:4}) However, I cannot figure out any way to insert "a" itself, specifying an id. In...

How to return value in Meteor.JS from HTTP.call “GET”


javascript,ajax,http,meteor,facebook-javascript-sdk
I'm writing a meteor method, which should return a Facebook response for HTTP.call on graph api, but HTTP.call has only a callback function to show error/response, so I can't take this data outside, and Method can not return any value. Here's my method code: loadUserFBEvents: function () { var accessToken...

Disabling tail.sh for specific server ( or environment )?


javascript,meteor
While testing my meteor app i keep receiving emails saying my application went offline. How does i disable this feature for an specific environment or hostname ( for instance, "localhost" ) ?...

using MongoDB aggregate count subdata


mongodb,aggregate
here is my data in mongodb: { "data": { "order_goods": [{ "category": 235 }, { "category": 666 }] } }, { "data": { order_goods: [{ "category": 235 }] } } here is my expected output: {"category":235, "total":2} {"category":666, "total":1} I have try many ways about aggregate such as $group, but...

Query an array of embedded documents in mongodb


mongodb,embedded-documents
I'm having a little trouble writing a query that needs to compare a given value against a certain field in all embedded documents within an array. I will give an example to make the issue less abstract. Let's say I want to use MongoDB to store the last queries that...

What is cursor?


meteor
In discover meteor, posts: function() { return Posts.find(); } is used, not this: posts: function() { return Posts.find().fetch(); } I tried function below, it also works, and can realtime update. What is cursor exactly? And What is the different of above two functions?...

Incorrect response to mapReduce query in mongo-db


mongodb,mapreduce
I have 1000 user records in collecton, in which 459 document has gender male and remaining as female //document structure > db.user_details.find().pretty() { "_id" : ObjectId("557e610d626754910f0974a4"), "id" : 0, "name" : "Leanne Flinn", "email" : "[email protected]", "work" : "Unilogic", "dob" : "Fri Jun 11 1965 20:50:58 GMT+0530 (IST)", "age" :...

Find Mongoid geospacial circles that contain a point


mongodb,mongoid,geospatial
I have Mongoid documents that represent services offered by local merchants. Each has one or more locations (lat/lng point) with a service area (radius). Given a customer location (lat/lng point), how can I find all the documents where the customer location falls within the service area? class Service include Mongoid::Document...

Compare Array with Collection-Array containing Objects


node.js,mongodb,mongoose,schema
This is my collection schema: var objectSchema = new Schema({ members: [{ user_id: ObjectId, settings: { type: Boolean } }], title: String }); And now I'm trying to search for objects with specific members (identified by their "user_id", for example ["asdf123lkd", "asdf1223"]). Is there any way to search for these...

Turning the Stripe Checkout into a Synch function


meteor,stripe-payments
I am trying to use wrapAsync for Stripe.charges call using Stripe Checkout, but I cant seem to get it working Client code Template.bookingPost2.events({ "click #accept": function(event, template){ event.preventDefault(); StripeCheckout.open({ key: 'public_key', amount: 5000, // this is equivalent to $50 name: 'Meteor Tutorial', description: 'On how to use Stripe ($50.00)', panelLabel:...

MeteorJS Blaze.getData() occasionally returns undefined


meteor,meteor-blaze
I'm currently rendering bootstrap modals on my webpage using MeteorJS's "renderWithData" method to load each template when it's needed. I'm running into an issue where my helper methods which access the data in the modal using "Blaze.getData()" will occasionally return undefined and I'm unsure how to fix that. The only...

TypeError: Cannot read property 'slice' of null


meteor,meteor-autoform,meteoric
I am using autoform in my project and getting this error when I open the form Not sure if this is because of any versions or dependency, my autoform is not working and I am getting this error, I have the screenshot and the schema code, form code below, template...

Getting failed to load c++ bson extension error using Mongodb and Node.js


javascript,node.js,mongodb
I am getting the following error while trying to run server using Node.ja with Mongodb. Error: { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++...

Use a “months” array to perform calculations for each month in a for loop


javascript,arrays,meteor,meteor-helper
I have a mongo collection to store "projects", each document stores a project with different calculations for each month of the year a_jan : 10, a_feb : 20, a_mar : 25, a_apr : 70 ... b_jan : 30, b_feb : 10, b_mar : 20, b_apr : 70 ... c_jan :...

Meteor collections: how to connect to different collections referring to each other?


meteor,meteor-helper,meteor-collections
I have two collections: Contracts = new Mongo.Collection('contracts'); Reminders = new Mongo.Collection('reminders'); These are structured in the database more or less like this: Contracts: { "id": "4432234", "contract": "C-42432432", "description": "Description of contract", "counterpart": "Company name", "status": "awarded" }, etc. Reminders: { "name": "Contract expiring", "type": "expiring", "contract": "C-42432432", "reminderDate":...

Use JSON file to insert data in database


javascript,json,mongodb,meteor,data
I'm using my JSON file like this to insert data in my collection : var content = JSON.parse(Assets.getText('test.json')); console.log('inserting...'); Profiles.insert({ user: id, data:content }; But I would like to have a "data's tree" like that : [ user: "rtegert23423131", firstname:"test", surname:"test2", // ... ] Not like that : [ user:...

Cassandra data model to store embedded documents


mongodb,database-design,cassandra
In mongodb we can able to store embedded documents into a collection.Then, How do we store embedded documents into cassandra??? For this sample JSON representation??? UserProfile = { name: "user profile", Dave Jones: { email: {name: "email", value: "[email protected]", timestamp: 125555555}, userName: {name: "userName", value: "Dave", timestamp: 125555555} }, Paul...

Why the query scans 8x times the documents it finds - MongoDB


mongodb
I've got 50 documents (for trial purposes) more or less like this one: "_id" : ObjectId("5461c8f0426f727f16010000"), "f" : [ { "t" : "ry", "v" : 1972 }, { "t" : "g", "v" : [ "Crime", "Drama" ] }, { "t" : "ml", "v" : "English" }, { "t" : "k",...

MongoJS - No Error On Unique Index


mongodb,mongojs
So I'm messing around with MongoDB using MongoJS and can't seem to get an error to be returned when a unique ID exists. So this is the code I am using: server.post('/register', function (req, res, next) { var details = req.params; details.password = md5(details.password).toString(); db.users.insert(details, function (err, test1, test2) {...