Search Results

Search found 29 results on 2 pages for 'mongoose'.

Page 1/2 | 1 2  | Next Page >

  • TypeError: Object {...} has no method 'find' - when using mongoose with express

    - by sdouble
    I'm having trouble getting data from MongoDB using mongoose schemas with express. I first tested with just mongoose in a single file (mongoosetest.js) and it works fine. But when I start dividing it all up with express routes and config files, things start to break. I'm sure it's something simple, but I've spent the last 3 hours googling and trying to figure out what I'm doing wrong and can't find anything that matches my process enough to compare. mongoosetest.js (this works fine, but not for my application) var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/meanstack'); var db = mongoose.connection; var userSchema = mongoose.Schema({ name: String }, {collection: 'users'}); var User = mongoose.model('User', userSchema); User.find(function(err, users) { console.log(users); }); These files are where I'm having issues. I'm sure it's something silly, probably a direct result of using external files, exports, and requires. My server.js file just starts up and configures express. I also have a routing file and a db config file. routing file (allRoutes.js) var express = require('express'); var router = express.Router(); var db = require('../config/db'); var User = db.User(); // routes router.get('/user/list', function(req, res) { User.find(function(err, users) { console.log(users); }); }); // catch-all route router.get('*', function(req, res) { res.sendfile('./public/index.html'); }); module.exports = router; dbconfig file (db.js) var mongoose = require('mongoose'); var dbHost = 'localhost'; var dbName = 'meanstack'; var db = mongoose.createConnection(dbHost, dbName); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; db.once('open', function callback() { console.log('connected'); }); // schemas var User = new Schema({ name : String }, {collection: 'users'}); // models mongoose.model('User', User); var User = mongoose.model('User'); //exports module.exports.User = User; I receive the following error when I browse to localhost:3000/user/list TypeError: Object { _id: 5398bed35473f98c494168a3 } has no method 'find' at Object.module.exports [as handle] (C:\...\routes\allRoutes.js:8:8) at next_layer (C:\...\node_modules\express\lib\router\route.js:103:13) at Route.dispatch (C:\...\node_modules\express\lib\router\route.js:107:5) at C:\...\node_modules\express\lib\router\index.js:213:24 at Function.proto.process_params (C:\...\node_modules\express\lib\router\index.js:284:12) at next (C:\...\node_modules\express\lib\router\index.js:207:19) at Function.proto.handle (C:\...\node_modules\express\lib\router\index.js:154:3) at Layer.router (C:\...\node_modules\express\lib\router\index.js:24:12) at trim_prefix (C:\...\node_modules\express\lib\router\index.js:255:15) at C:\...\node_modules\express\lib\router\index.js:216:9 Like I said, it's probably something silly that I'm messing up with trying to organize my code since my single file (mongoosetest.js) works as expected. Thanks.

    Read the article

  • When to save a mongoose model

    - by kentcdodds
    This is an architectural question. I have models like this: var foo = new mongoose.Schema({ name: String, bars: [{type: ObjectId, ref: 'Bar'}] }); var FooModel = mongoose.model('Foo', foo); var bar = new mongoose.Schema({ foobar: String }); var BarModel = mongoose.model('Bar', bar); Then I want to implement a convenience method like this: BarModel.methods.addFoo = function(foo) { foo.bars = foo.bars || []; // Side note, is this something I should check here? foo.bars.push(this.id); // Here's the line I'm wondering about... Should I include the line below? foo.save(); } The biggest con I see about this is that if I did include foo.save() then I should pass in a callback to addFoo so I avoid issues with the async operation. I'm thinking this is not preferable. But I also think it would be nice to include because addFoo hasn't really "addedFoo" until it's been saved... Am I breaking any design best practices doing it either way?

    Read the article

  • Mongoose Not Creating Indexes

    - by wintzer
    I have been trying all afternoon to get my node.js application to create MongoDB indexes properly. I am using the Mongoose ODM and in my schema definition below I have the username field set to a unique index. The collection and document all get created properly, it's just the indexes that aren't working. All the documentation says that the ensureIndex command should be run at startup to create any indexes, but none are being made. I'm using MongoLab for hosting if that matters. I have also repeatedly dropped the collection. Please tell me what I'm doing wrong. var schemaUser = new mongoose.Schema({ username: {type: String, index: { unique: true }, required: true}, hash: String, created: {type: Date, default: Date.now} }, { collection:'Users' }); var User = mongoose.model('Users', schemaUser); var newUser = new Users({username:'wintzer'}) newUser.save(function(err) { if (err) console.log(err); });

    Read the article

  • Saving in mongoDb with Mongoose, unexpected elements saved

    - by guiomie
    When I write in my mongoDB with mongoose the operation is treated with success, my document is saved, but there is also all kind of weird other sutff written down. It seems to be mongoose code. What could cause this? I add stuff in a specific array with: resultReference.ref[arrayLocation].allEvents.push(theEvent); {id: 11, allEvents: [] } is the structure of a ref element, and I push theEvent in the allEvents array. I then resultReference.save() I use express, mongoose and mongoHQ for database. I tried on a local mongo server, and this annoyance is still there. I've print in my console the document to write before save() and non of this weird code is there. { id 11 allEvents [ 0 { _events { maxListeners 0 } _doc { _id {"$oid": "4eb87834f54944e263000003"} title "Test" allDay false start 2011-11-10 13:00:00 UTC end 2011-11-10 15:00:00 UTC url "/test/4eb87834f54944e263000002" color "#99CCFF" ref "4eb87834f54944e263000002" } _activePaths { paths { title "modify" allDay "modify" start "modify" end "modify" url "modify" color "modify" ref "modify" } states { init { } modify { title true allDay true start true end true url true color true ref true } require { } } stateNames [ 0 "require" 1 "modify" 2 "init" ] } _saveError null _validationError null isNew true _pres { save [ 0 function (next) { // we keep the error semaphore to make sure we don't // call `save` unnecessarily (we only need 1 error) var subdocs = 0 , error = false , self = this; var arrays = this._activePaths .map('init', 'modify', function (i) { return self.getValue(i); }) .filter(function (val) { return (val && val instanceof DocumentArray && val.length); }); if (!arrays.length) return next(); arrays.forEach(function (array) { subdocs += array.length; array.forEach(function (value) { if (!error) value.save(function (err) { if (!error) { if (err) { error = true; next(err); } else --subdocs || next(); } }); }); }); } 1 "function checkForExistingErrors(next) { if (self._saveError){ next(self._saveError); self._saveError = null; } else { next(); } }" 2 "function validation(next) { return self.validate.call(self, next); }" ] } _posts { save [ ] } save function () { var self = this , hookArgs // arguments eventually passed to the hook - are mutable , lastArg = arguments[arguments.length-1] , pres = this._pres[name] , posts = this._posts[name] , _total = pres.length , _current = -1 , _asyncsLeft = proto[name].numAsyncPres , _next = function () { if (arguments[0] instanceof Error) { return handleError(arguments[0]); } var _args = Array.prototype.slice.call(arguments) , currPre , preArgs; if (_args.length && !(arguments[0] === null && typeof lastArg === 'function')) hookArgs = _args; if (++_current < _total) { currPre = pres[_current] if (currPre.isAsync && currPre.length < 2) throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); if (currPre.length < 1) throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); preArgs = (currPre.isAsync ? [once(_next), once(_asyncsDone)] : [once(_next)]).concat(hookArgs); return currPre.apply(self, preArgs); } else if (!proto[name].numAsyncPres) { return _done.apply(self, hookArgs); } } , _done = function () { var args_ = Array.prototype.slice.call(arguments) , ret, total_, current_, next_, done_, postArgs; if (_current === _total) { ret = fn.apply(self, args_); total_ = posts.length; current_ = -1; next_ = function () { if (arguments[0] instanceof Error) { return handleError(arguments[0]); } var args_ = Array.prototype.slice.call(arguments, 1) , currPost , postArgs; if (args_.length) hookArgs = args_; if (++current_ < total_) { currPost = posts[current_] if (currPost.length < 1) throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); postArgs = [once(next_)].concat(hookArgs); return currPost.apply(self, postArgs); } }; if (total_) return next_(); return ret; } }; if (_asyncsLeft) { function _asyncsDone (err) { if (err && err instanceof Error) { return handleError(err); } --_asyncsLeft || _done.apply(self, hookArgs); } } function handleError (err) { if ('function' == typeof lastArg) return lastArg(err); if (errorCb) return errorCb.call(self, err); throw err; } return _next.apply(this, arguments); } errors null } ] } ]

    Read the article

  • Contains Query into MongoDB Array using Mongoose

    - by Nilay Parikh
    I'm trying to query into following document and want to list all document which contains TaxonomyID "1" in "TaxonomyIDs" field. ... "Slug" : "videosecu-600tvl-outdoor-security-surveillance", "Category" : "Digital Cameras", "SubCategory" : "Surveillance Cameras", "Segment" : "", "Usabilities" : [ "Dome Cameras", "Night Vision" ], "TaxonomyIDs" : [ 1, 12, 20, 21, 13 ], "Brand" : "VideoSecu", ... Totally stuck!

    Read the article

  • mongoose updating a field in a MongoDB not working

    - by Masiar
    I have this code var UserSchema = new Schema({ Username: {type: String, index: true}, Password: String, Email: String, Points: {type: Number, default: 0} }); [...] var User = db.model('User'); /* * Function to save the points in the user's account */ function savePoints(name, points){ if(name != "unregistered user"){ User.find({Username: name}, function(err, users){ var oldPoints = users[0].Points; var newPoints = oldPoints + points; User.update({name: name}, { $inc: {Points: newPoints}}, function(err){ if(err){ console.log("some error happened when update"); } else{ console.log("update successfull! with name = " + name); User.find({Username: name}, function(err, users) { console.log("updated : " + users[0].Points); }); } }); }); } } savePoints("Masiar", 666); I would like to update my user (by finding it with its name) by updating his/her points. I'm sure oldPoints and points contain a value, but still my user keep being at zero points. The console prints "update successful". What am I doing wrong? Sorry for the stupid / noob question. Masiar

    Read the article

  • making a password-only auth with bcrypt and mongoose

    - by user3081123
    I want to create service that let you login only with password. You type a password and if this password exists - you are logged in and if it's not - username is generated and password is encrypted. I'm having some misunderstandings and hope someone would help me to show where I'm mistaken. I guess, it would look somewhat like this in agularjs First we receive a password in login controller. $scope.signup = function() { var user = { password: $scope.password, }; $http.post('/auth/signup', user); }; Send it via http.post and get in in our node server file. We are provided with a compare password bcrypt function userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; So right now we are creating function to catch our http request app.post('/auth/signup', function(req, res, next) { Inside we use a compair password function to realize if such password exists or not yet. So we have to encrypt a password with bcrypt to make a comparison First we hash it same way as in .pre var encPass; bcrypt.genSalt(10, function(err, salt) { if (err) return next(err); bcrypt.hash(req.body.password, salt, function(err, hash) { if (err) return next(err); encPass=hash; )}; )}; We have encrypted password stored in encPass so now we follow to finding a user in database with this password User.findOne({ password: encPass }, function(err, user) { if (user) { //user exists, it means we should pass an ID of this user to a controller to display it in a view. I don't know how. res.send({user.name}) //like this? How should controller receive this? With $http.post? } else { and now if user doesn't exist - we should create it with user ID generated by my function var nUser = new User({ name: generId(), password: req.body.password }); nUser.save(function(err) { if (err) return next(err); )}; )}; )}; Am I doing anything right? I'm pretty new to js and angular. If so - how do I throw a username back at controller? If someone is interested - this service exists for 100+ symbol passphrases so possibility of entering same passphrase as someone else is miserable. And yeah, If someone logged in under 123 password - the other guy will log in as same user if he entered 123 password, but hey, you are warned to make a big passphrase. So I'm confident about the idea and I only need a help with understanding and realization.

    Read the article

  • Mongoose 3.1.0: Why the callback in the connection.db.dropDatabase(callback) is never called?

    - by Totty
    Code: var connection = mongoose.createConnection('mongodb://localhost:9000/' + databaseName); connection.db.dropDatabase(function(err){ // never reach this point! debugger; console.log(err); console.log('-------------->Dropped database: ' + databaseName); }); If I do connection.open it says that it's already opening and no multiple calls to "open" are supported for the same connection. Even this doesn't work var conn = mongoose.createConnection('mongodb://localhost',databaseName, 9000, {}, function(){ console.log('created'); // is reached conn.db.dropDatabase(callback); // but the callback is not called anyway }); What is the problem? ("mongoose": "3.1.0") thanks

    Read the article

  • getting data from dynamic schema

    - by coure2011
    I am using mongoose/nodejs to get data as json from mongodb. For using mongoose I need to define schema first like this var mongoose = require('mongoose'); var Schema = mongoose.Schema; var GPSDataSchema = new Schema({ createdAt: { type: Date, default: Date.now } ,speed: {type: String, trim: true} ,battery: { type: String, trim: true } }); var GPSData = mongoose.model('GPSData', GPSDataSchema); mongoose.connect('mongodb://localhost/gpsdatabase'); var db = mongoose.connection; db.on('open', function() { console.log('DB Started'); }); then in code I can get data from db like GPSData.find({"createdAt" : { $gte : dateStr, $lte: nextDate }}, function(err, data) { res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }); var body = JSON.stringify(data); res.end(body); }); How to define scheme for a complex data like this, you can see that subSection can go to any deeper level. [ { 'title': 'Some Title', 'subSection': [{ 'title': 'Inner1', 'subSection': [ {'titile': 'test', 'url': 'ab/cd'} ] }] }, .. ]

    Read the article

  • Node.js mongoose: how to use the .in and .sort methods of a query?

    - by Chris
    Hi there, I'm trying to wrap my head around mongoose, but I'm having a hard time finding any kind of documentation for some of the more advanced query options, specifically the .in and .sort methods. What's the syntax for sorting, for example, a Person by age? db.model("Person").find().sort(???).all(function(people) { }); Then, let's say I want to find a Movie based on a genre, where a Movie can have many genres (in this case, an array of strings). Presumably, I'd use the .in function to accomplish that, but I'm not sure what the syntax would be. Or perhaps I don't have to use the .in method at all...? Either way, I'm lost. db.model("Movie").find().in(???).all(function(movies) { }); Anyone have any ideas? Or even better, a link to some comprehensive documentation? Thanks! Chris

    Read the article

  • Should a complete newbie use mongoose js? [on hold]

    - by Squirrl
    I drank from the koolaid and jumped aboard the node.js bandwagon even though I barely know javascript. That said, I have the opportunity to work with one of 2 templates. One is just node, express and mongodb, and the second includes mongoose and jade with the other 3 and is easier for me to understand. Yet I'm concerned that if I begin with mongoose, I'll be too high level and miss some of the fundamentals. Is my concern warranted? Should I work my way up or should I just start playing with all the toys from day one?

    Read the article

  • How to filter Backbone.js Collection and Rerender App View?

    - by Jeremy H.
    Is is a total Backbone.js noob question. I am working off of the ToDo Backbone.js example trying to build out a fairly simple single app interface. While the todo project is more about user input, this app is more about filtering the data based on the user options (click events). I am completely new to Backbone.js and Mongoose and have been unable to find a good example of what I am trying to do. I have been able to get my api to pull the data from the MongoDB collection and drop it into the Backbone.js collection which renders it in the app. What I cannot for the life of me figure out how to do is filter that data and re-render the app view. I am trying to filter by the "type" field in the document. Here is my script: (I am totally aware of some major refactoring needed, I am just rapid prototyping a concept.) $(function() { window.Job = Backbone.Model.extend({ idAttribute: "_id", defaults: function() { return { attachments: false } } }); window.JobsList = Backbone.Collection.extend({ model: Job, url: '/api/jobs', leads: function() { return this.filter(function(job){ return job.get('type') == "Lead"; }); } }); window.Jobs = new JobsList; window.JobView = Backbone.View.extend({ tagName: "div", className: "item", template: _.template($('#item-template').html()), initialize: function() { this.model.bind('change', this.render, this); this.model.bind('destroy', this.remove, this); }, render: function() { $(this.el).html(this.template(this.model.toJSON())); this.setText(); return this; }, setText: function() { var month=new Array(); month[0]="Jan"; month[1]="Feb"; month[2]="Mar"; month[3]="Apr"; month[4]="May"; month[5]="Jun"; month[6]="Jul"; month[7]="Aug"; month[8]="Sep"; month[9]="Oct"; month[10]="Nov"; month[11]="Dec"; var title = this.model.get('title'); var description = this.model.get('description'); var datemonth = this.model.get('datem'); var dateday = this.model.get('dated'); var jobtype = this.model.get('type'); var jobstatus = this.model.get('status'); var amount = this.model.get('amount'); var paymentstatus = this.model.get('paymentstatus') var type = this.$('.status .jobtype'); var status = this.$('.status .jobstatus'); this.$('.title a').text(title); this.$('.description').text(description); this.$('.date .month').text(month[datemonth]); this.$('.date .day').text(dateday); type.text(jobtype); status.text(jobstatus); if(amount > 0) this.$('.paymentamount').text(amount) if(paymentstatus) this.$('.paymentstatus').text(paymentstatus) if(jobstatus === 'New') { status.addClass('new'); } else if (jobstatus === 'Past Due') { status.addClass('pastdue') }; if(jobtype === 'Lead') { type.addClass('lead'); } else if (jobtype === '') { type.addClass(''); }; }, remove: function() { $(this.el).remove(); }, clear: function() { this.model.destroy(); } }); window.AppView = Backbone.View.extend({ el: $("#main"), events: { "click #leads .highlight" : "filterLeads" }, initialize: function() { Jobs.bind('add', this.addOne, this); Jobs.bind('reset', this.addAll, this); Jobs.bind('all', this.render, this); Jobs.fetch(); }, addOne: function(job) { var view = new JobView({model: job}); this.$("#activitystream").append(view.render().el); }, addAll: function() { Jobs.each(this.addOne); }, filterLeads: function() { // left here, this event fires but i need to figure out how to filter the activity list. } }); window.App = new AppView; });

    Read the article

  • MongoDB using NOT and AND together

    - by Stankalank
    I'm trying to negate an $and clause with MongoDB and I'm getting a MongoError: invalid operator: $and message back. Basically what I want to achieve is the following: query = { $not: { $and: [{institution_type:'A'}, {type:'C'}] } } Is this possible to express in a mongo query? Here is a sample collection: { "institution_type" : "A", "type" : "C" } { "institution_type" : "A", "type" : "D" } { "institution_type" : "B", "type" : "C" } { "institution_type" : "B", "type" : "D" } What I want to get back is the following: { "institution_type" : "A", "type" : "D" } { "institution_type" : "B", "type" : "C" } { "institution_type" : "B", "type" : "D" }

    Read the article

  • Why do node packages put a comma on a newline?

    - by SomeKittens
    I'm learning node.js and am trying out Express. My first app had this code: var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path'); Reading through the mongoose tutorial gives me this: var mongoose = require('mongoose') , db = mongoose.createConnection('localhost', 'test'); On strict mode, JSHint gives me app.js: line 6, col 32, Bad line breaking before ','. Which shows that I'm not the only one out there who's bugged by this syntax. Is there any reason to declare vars this way instead of adding the comma at the end of the line?

    Read the article

  • Windows Azure: Major Updates for Mobile Backend Development

    - by ScottGu
    This week we released some great updates to Windows Azure that make it significantly easier to develop mobile applications that use the cloud. These new capabilities include: Mobile Services: Custom API support Mobile Services: Git Source Control support Mobile Services: Node.js NPM Module support Mobile Services: A .NET API via NuGet Mobile Services and Web Sites: Free 20MB SQL Database Option for Mobile Services and Web Sites Mobile Notification Hubs: Android Broadcast Push Notification Support All of these improvements are now available to use immediately (note: some are still in preview).  Below are more details about them. Mobile Services: Custom APIs, Git Source Control, and NuGet Windows Azure Mobile Services provides the ability to easily stand up a mobile backend that can be used to support your Windows 8, Windows Phone, iOS, Android and HTML5 client applications.  Starting with the first preview we supported the ability to easily extend your data backend logic with server side scripting that executes as part of client-side CRUD operations against your cloud back data tables. With today’s update we are extending this support even further and introducing the ability for you to also create and expose Custom APIs from your Mobile Service backend, and easily publish them to your Mobile clients without having to associate them with a data table. This capability enables a whole set of new scenarios – including the ability to work with data sources other than SQL Databases (for example: Table Services or MongoDB), broker calls to 3rd party APIs, integrate with Windows Azure Queues or Service Bus, work with custom non-JSON payloads (e.g. Windows Periodic Notifications), route client requests to services back on-premises (e.g. with the new Windows Azure BizTalk Services), or simply implement functionality that doesn’t correspond to a database operation.  The custom APIs can be written in server-side JavaScript (using Node.js) and can use Node’s NPM packages.  We will also be adding support for custom APIs written using .NET in the future as well. Creating a Custom API Adding a custom API to an existing Mobile Service is super easy.  Using the Windows Azure Management Portal you can now simply click the new “API” tab with your Mobile Service, and then click the “Create a Custom API” button to create a new Custom API within it: Give the API whatever name you want to expose, and then choose the security permissions you’d like to apply to the HTTP methods you expose within it.  You can easily lock down the HTTP verbs to your Custom API to be available to anyone, only those who have a valid application key, only authenticated users, or administrators.  Mobile Services will then enforce these permissions without you having to write any code: When you click the ok button you’ll see the new API show up in the API list.  Selecting it will enable you to edit the default script that contains some placeholder functionality: Today’s release enables Custom APIs to be written using Node.js (we will support writing Custom APIs in .NET as well in a future release), and the Custom API programming model follows the Node.js convention for modules, which is to export functions to handle HTTP requests. The default script above exposes functionality for an HTTP POST request. To support a GET, simply change the export statement accordingly.  Below is an example of some code for reading and returning data from Windows Azure Table Storage using the Azure Node API: After saving the changes, you can now call this API from any Mobile Service client application (including Windows 8, Windows Phone, iOS, Android or HTML5 with CORS). Below is the code for how you could invoke the API asynchronously from a Windows Store application using .NET and the new InvokeApiAsync method, and data-bind the results to control within your XAML:     private async void RefreshTodoItems() {         var results = await App.MobileService.InvokeApiAsync<List<TodoItem>>("todos", HttpMethod.Get, parameters: null);         ListItems.ItemsSource = new ObservableCollection<TodoItem>(results);     }    Integrating authentication and authorization with Custom APIs is really easy with Mobile Services. Just like with data requests, custom API requests enjoy the same built-in authentication and authorization support of Mobile Services (including integration with Microsoft ID, Google, Facebook and Twitter authentication providers), and it also enables you to easily integrate your Custom API code with other Mobile Service capabilities like push notifications, logging, SQL, etc. Check out our new tutorials to learn more about to use new Custom API support, and starting adding them to your app today. Mobile Services: Git Source Control Support Today’s Mobile Services update also enables source control integration with Git.  The new source control support provides a Git repository as part your Mobile Service, and it includes all of your existing Mobile Service scripts and permissions. You can clone that git repository on your local machine, make changes to any of your scripts, and then easily deploy the mobile service to production using Git. This enables a really great developer workflow that works on any developer machine (Windows, Mac and Linux). To use the new support, navigate to the dashboard for your mobile service and select the Set up source control link: If this is your first time enabling Git within Windows Azure, you will be prompted to enter the credentials you want to use to access the repository: Once you configure this, you can switch to the configure tab of your Mobile Service and you will see a Git URL you can use to use your repository: You can use this URL to clone the repository locally from your favorite command line: > git clone https://scottgutodo.scm.azure-mobile.net/ScottGuToDo.git Below is the directory structure of the repository: As you can see, the repository contains a service folder with several subfolders. Custom API scripts and associated permissions appear under the api folder as .js and .json files respectively (the .json files persist a JSON representation of the security settings for your endpoints). Similarly, table scripts and table permissions appear as .js and .json files, but since table scripts are separate per CRUD operation, they follow the naming convention of <tablename>.<operationname>.js. Finally, scheduled job scripts appear in the scheduler folder, and the shared folder is provided as a convenient location for you to store code shared by multiple scripts and a few miscellaneous things such as the APNS feedback script. Lets modify the table script todos.js file so that we have slightly better error handling when an exception occurs when we query our Table service: todos.js tableService.queryEntities(query, function(error, todoItems){     if (error) {         console.error("Error querying table: " + error);         response.send(500);     } else {         response.send(200, todoItems);     }        }); Save these changes, and now back in the command line prompt commit the changes and push them to the Mobile Services: > git add . > git commit –m "better error handling in todos.js" > git push Once deployment of the changes is complete, they will take effect immediately, and you will also see the changes be reflected in the portal: With the new Source Control feature, we’re making it really easy for you to edit your mobile service locally and push changes in an atomic fashion without sacrificing ease of use in the Windows Azure Portal. Mobile Services: NPM Module Support The new Mobile Services source control support also allows you to add any Node.js module you need in the scripts beyond the fixed set provided by Mobile Services. For example, you can easily switch to use Mongo instead of Windows Azure table in our example above. Set up Mongo DB by either purchasing a MongoLab subscription (which provides MongoDB as a Service) via the Windows Azure Store or set it up yourself on a Virtual Machine (either Windows or Linux). Then go the service folder of your local git repository and run the following command: > npm install mongoose This will add the Mongoose module to your Mobile Service scripts.  After that you can use and reference the Mongoose module in your custom API scripts to access your Mongo database: var mongoose = require('mongoose'); var schema = mongoose.Schema({ text: String, completed: Boolean });   exports.get = function (request, response) {     mongoose.connect('<your Mongo connection string> ');     TodoItemModel = mongoose.model('todoitem', schema);     TodoItemModel.find(function (err, items) {         if (err) {             console.log('error:' + err);             return response.send(500);         }         response.send(200, items);     }); }; Don’t forget to push your changes to your mobile service once you are done > git add . > git commit –m "Switched to use Mongo Labs" > git push Now our Mobile Service app is using Mongo DB! Note, with today’s update usage of custom Node.js modules is limited to Custom API scripts only. We will enable it in all scripts (including data and custom CRON tasks) shortly. New Mobile Services NuGet package, including .NET 4.5 support A few months ago we announced a new pre-release version of the Mobile Services client SDK based on portable class libraries (PCL). Today, we are excited to announce that this new library is now a stable .NET client SDK for mobile services and is no longer a pre-release package. Today’s update includes full support for Windows Store, Windows Phone 7.x, and .NET 4.5, which allows developers to use Mobile Services from ASP.NET or WPF applications. You can install and use this package today via NuGet. Mobile Services and Web Sites: Free 20MB Database for Mobile Services and Web Sites Starting today, every customer of Windows Azure gets one Free 20MB database to use for 12 months free (for both dev/test and production) with Web Sites and Mobile Services. When creating a Mobile Service or a Web Site, simply chose the new “Create a new Free 20MB database” option to take advantage of it: You can use this free SQL Database together with the 10 free Web Sites and 10 free Mobile Services you get with your Windows Azure subscription, or from any other Windows Azure VM or Cloud Service. Notification Hubs: Android Broadcast Push Notification Support Earlier this year, we introduced a new capability in Windows Azure for sending broadcast push notifications at high scale: Notification Hubs. In the initial preview of Notification Hubs you could use this support with both iOS and Windows devices.  Today we’re excited to announce new Notification Hubs support for sending push notifications to Android devices as well. Push notifications are a vital component of mobile applications.  They are critical not only in consumer apps, where they are used to increase app engagement and usage, but also in enterprise apps where up-to-date information increases employee responsiveness to business events.  You can use Notification Hubs to send push notifications to devices from any type of app (a Mobile Service, Web Site, Cloud Service or Virtual Machine). Notification Hubs provide you with the following capabilities: Cross-platform Push Notifications Support. Notification Hubs provide a common API to send push notifications to iOS, Android, or Windows Store at once.  Your app can send notifications in platform specific formats or in a platform-independent way.  Efficient Multicast. Notification Hubs are optimized to enable push notification broadcast to thousands or millions of devices with low latency.  Your server back-end can fire one message into a Notification Hub, and millions of push notifications can automatically be delivered to your users.  Devices and apps can specify a number of per-user tags when registering with a Notification Hub. These tags do not need to be pre-provisioned or disposed, and provide a very easy way to send filtered notifications to an infinite number of users/devices with a single API call.   Extreme Scale. Notification Hubs enable you to reach millions of devices without you having to re-architect or shard your application.  The pub/sub routing mechanism allows you to broadcast notifications in a super-efficient way.  This makes it incredibly easy to route and deliver notification messages to millions of users without having to build your own routing infrastructure. Usable from any Backend App. Notification Hubs can be easily integrated into any back-end server app, whether it is a Mobile Service, a Web Site, a Cloud Service or an IAAS VM. It is easy to configure Notification Hubs to send push notifications to Android. Create a new Notification Hub within the Windows Azure Management Portal (New->App Services->Service Bus->Notification Hub): Then register for Google Cloud Messaging using https://code.google.com/apis/console and obtain your API key, then simply paste that key on the Configure tab of your Notification Hub management page under the Google Cloud Messaging Settings: Then just add code to the OnCreate method of your Android app’s MainActivity class to register the device with Notification Hubs: gcm = GoogleCloudMessaging.getInstance(this); String connectionString = "<your listen access connection string>"; hub = new NotificationHub("<your notification hub name>", connectionString, this); String regid = gcm.register(SENDER_ID); hub.register(regid, "myTag"); Now you can broadcast notification from your .NET backend (or Node, Java, or PHP) to any Windows Store, Android, or iOS device registered for “myTag” tag via a single API call (you can literally broadcast messages to millions of clients you have registered with just one API call): var hubClient = NotificationHubClient.CreateClientFromConnectionString(                   “<your connection string with full access>”,                   "<your notification hub name>"); hubClient.SendGcmNativeNotification("{ 'data' : {'msg' : 'Hello from Windows Azure!' } }", "myTag”); Notification Hubs provide an extremely scalable, cross-platform, push notification infrastructure that enables you to efficiently route push notification messages to millions of mobile users and devices.  It will make enabling your push notification logic significantly simpler and more scalable, and allow you to build even better apps with it. Learn more about Notification Hubs here on MSDN . Summary The above features are now live and available to start using immediately (note: some of the services are still in preview).  If you don’t already have a Windows Azure account, you can sign-up for a free trial and start using them today.  Visit the Windows Azure Developer Center to learn more about how to build apps with it. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • ansi-c fscanf problem

    - by mongoose
    hi i read the file as follows fscanf(fp,"%f %f %f",&*(p1+i), &*(p2+i), &*(p3+i)); my file's lines consists of three floating point numbers... the problem i have is that in the file let's say i have some floating points with let's say maximum of two digits after the dot. but when i ask c to print those values using different formatting, for example %lf,%.2lf,%.4lf... it starts to play with the digits... my only concern is this, if i have let's say 1343.23 in the file, then will c use this value exactly as it is in computations or it will play with the digits after the dot. if it will play, then how is it possible to make it so that it uses floating point numbers exactly as they are? for example in last case even if i ask it to print that value using %.10lf i would expect it to print only 1343.2300000000.? thanks a lot!

    Read the article

  • Node.js server crashes , Database operations halfway?

    - by Ranadeep
    I have a node.js app with mongodb backend going to production in a week and i have few doubts on how to handle app crashes and restart . Say i have a simple route /followUser in which i have 2 database operations /followUser ----->Update User1 Document.followers = User2 ----->Update User2 Document.followers = User1 ----->Some other mongodb(via mongoose)operation What happens if there is a server crash(due to power failure or maybe the remote mongodb server is down ) like this scenario : ----->Update User1 Document.followers = User2 SERVER CRASHED , FOREVER RESTARTS NODE What happens to these operations below ? The system is now in inconsistent state and i may have error everytime i ask for User2 followers ----->Update User2 Document.followers = User1 ----->Some other mongodb(via mongoose)operation Also please recommend good logging and restart/monitor modules for apps running in linux

    Read the article

  • MongoDB query against geospatial index with maxDistance fails from node.js client

    - by user1735497
    I want to query against a geospatial index in mongo-db (designed after this tutorial http://www.mongodb.org/display/DOCS/Geospatial+Indexing). So when I execute this from the shell everything works fine: db.sellingpoints.find(( { location : { $near: [48.190120, 16.270895], $maxDistance: 7 / 111.2 } } ); but the same query from my nodejs application (using mongoskin or mongoose), won't return any results until i set the distance-value to a very high number (5690) db.collection('sellingpoints') .find({ location: { $near: [lat,lng], $maxDistance: distance / 111.2} }) .limit(limit) .toArray(callback); Has someone any idea how to fix that?

    Read the article

  • nodejs server hanging from time to time

    - by Johann Philipp Strathausen
    I have a node server (0.6.6) running an Express application, along with Mongoose and s3, on an Ubuntu 11.04 machine. Several times per hour, the server is hanging. That means that the application is working fine, I see the express loggings, and then all of a sudden the server stops responding. No errors, no traces, no loggings, and strangely enough the browser won't show the request even in the network debugging window. From any machine in the local network it's the same behaviour. I restart the server and it's okay again for several minutes, then again starts to hang, everytime while doing something different. The same application on Amazon on the same Ubuntu version works fine and never hangs. I know all this is kind of vague, but I don't know where to start. Has any of you seen something like this before? Any idea?

    Read the article

  • Compact web server with Lua support?

    - by OverTheRainbow
    Hello, I need to find a very compact, cross-platform web server that can run Lua scripts, ie. either a regular web server like Mongoose that will forward queries to a Lua program in eg. FastCGI, or a web server itself written in Lua which will save the need to provide a separate web server. I recently started learning about Lua so am still in the dark about what is available out there, save for the three I came accross: Barracuda Embedded Web Server http://barracudaserver.com/ba/doc/ Xavante - Lua HTTP 1.1 Web server http://keplerproject.github.com/xavante/ Haserl http://haserl.sourceforge.net/ If someone's already done this recently, what solution would you recommend along with any tutorial/article that would get me started? Thank you.

    Read the article

  • Possible to host CentOS netinstall files on a local HTTP/FTP?

    - by garlicman
    I'm running XenServer on an Dell R610 and am running into a catch-22. During install from DVD, CentOS can't find the DVD package catalogue. It's a reported error for some, XenServer + CentOS6 + DVD install in some hardware configurations = failed install. Yes, I checked the MD5 and let the disc test pass. In every reported case, the netinstall was the solution. The issue is my net access is required to go through a web proxy that prompts before you can download a file. This naturally breaks any download automation. I've been waiting on our IT to put in an exception rule to allow my lab to bypass the prompt, but it's been over 3 weeks now and they don't seem responsive. (I've been working on this a day or two a week) I want to try and host the netinstall files local in my Xen network. Right now I only have a bunch of Windows based VMs, CentOS won't install so I don't have any Linux tools. I had tried simply hosting all the DVD contents off one of the Windows servers using Mongoose. (I didn't want to setup IIS) I copied them to a hosted sub-directory similar to all the mirrors out there (e.g. http:///centos/6.2/os/i386/) with no auth or anything. Then in the netinstall I correctly pointed to it. I now realize just copying the DVD files over won't work. The repodata will point to a local device, not the site I'm hosting. (e.g. the DVD repodata includes xml that points to where the packages are) Clearly I'm hosting them over HTTP, not from a DVD. Is there an easy way to sort this out? I'm just trying to install CentOS6 on Xen. If there's a turnkey downloadable Xen image with CentOS 6.2 on it, or a downloadable repo image, I'll take that too! Thank you in advance!

    Read the article

  • What is a suitable simple, open web server for Windows?

    - by alficles
    I'm looking for a dead simple web server for Windows. Load will not be high as it will be primarily serving binaries for a WPKG update service. It needs to serve the entire contents of a single folder over HTTP on a configurable (high) port. No CGI or other scripting is required, but it might be nice for future features. I started with Mongoose, since it doesn't even have an installation requirement (a very nice perk), but it fails to start when run as a service. (Technically, it acts as it's own installer.) I've investigated LighTPD as well, but it appears to be minimally (at best) tested on Windows. And naturally, I'm looking for something free. As in beer is good, but speech is better, as always. Edit: I didn't mention this initially, but non-tech people will be doing the install. They'll have whatever script I write for the install, but the goal is a simple system that is easy to troubleshoot. (I almost worded this question "What is the best...", but Serverfault rightly observed that that is a subjective question. And it's really not an optimization problem, any suitable solution will work. I just can't seem to find one for Windows.)

    Read the article

  • Node.js + express.js + passport.js : stay authenticated between server restart

    - by Arnaud Rinquin
    I use passport.js to handle auth on my nodejs + express.js application. I setup a LocalStrategy to take users from mongodb My problems is that users have to re-authenticate when I restart my node server. This is a problem as I am actively developing it and don't wan't to login at every restart... (+ I use node supervisor) Here is my app setup : app.configure(function(){ app.use('/static', express.static(__dirname + '/static')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({secret:'something'})); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); }); And session serializing setup : passport.serializeUser(function(user, done) { done(null, user.email); }); passport.deserializeUser(function(email, done) { User.findOne({email:email}, function(err, user) { done(err, user); }); }); I tried the solution given on this blog using connect-mongodb without success app.use(express.session({ secret:'something else', cookie: {maxAge: 60000 * 60 * 24 * 30}, // 30 days store: MongoDBStore({ db: mongoose.connection.db }) }));

    Read the article

  • How to change scope data in controller?

    - by Derooie
    I am a real newbie at angular. I created something now which will let me retrieve and add items via angular and get/put them in mongodb. I use express and mongoose in the app The question is, how can i modify the data before it reaches the DOM in the controller. In this example i have created a way to retrieve data, and i get it exactly as it is stored in mongodb. What i would like is that the field where i store 1 or 0 in the database, to be shown as text. So if mongo has a value 1 i get "the value in mongo is 1" and when the field has a value of 0 get "the value is zero". (just as an example, i like other texts, but it illustrate what i want) I post my controller, html and current output. Any help would be appreciated. Controller function getGuests($scope, $http) { $scope.formData = {}; $http.get('/api/guests') .success(function(data) { $scope.x = data; }) .error(function(data) { console.log('Error: ' + data); }); } HTML <div ng-controller="getGuests"> <div ng-repeat="guest in x"> {{ guest.voornaam }} {{ guest.aanwezig }} </div> </div> The current scope output, what i see in HTML. I like to change only the value of "aanwezig" in case the value of aanwezig is 0 or 1. firstname1 1 firstname2 0 Something else, but would be great to learn, is how i can do a specific mongodb query by the push of a button and get that result.

    Read the article

  • Learning AngularJS by Example – The Customer Manager Application

    - by dwahlin
    I’m always tinkering around with different ideas and toward the beginning of 2013 decided to build a sample application using AngularJS that I call Customer Manager. It’s not exactly the most creative name or concept, but I wanted to build something that highlighted a lot of the different features offered by AngularJS and how they could be used together to build a full-featured app. One of the goals of the application was to ensure that it was approachable by people new to Angular since I’ve never found overly complex applications great for learning new concepts. The application initially started out small and was used in my AngularJS in 60-ish Minutes video on YouTube but has gradually had more and more features added to it and will continue to be enhanced over time. It’ll be used in a new “end-to-end” training course my company is working on for AngularjS as well as in some video courses that will be coming out. Here’s a quick look at what the application home page looks like: In this post I’m going to provide an overview about how the application is organized, back-end options that are available, and some of the features it demonstrates. I’ve already written about some of the features so if you’re interested check out the following posts: Building an AngularJS Modal Service Building a Custom AngularJS Unique Value Directive Using an AngularJS Factory to Interact with a RESTful Service Application Structure The structure of the application is shown to the right. The  homepage is index.html and is located at the root of the application folder. It defines where application views will be loaded using the ng-view directive and includes script references to AngularJS, AngularJS routing and animation scripts, plus a few others located in the Scripts folder and to custom application scripts located in the app folder. The app folder contains all of the key scripts used in the application. There are several techniques that can be used for organizing script files but after experimenting with several of them I decided that I prefer things in folders such as controllers, views, services, etc. Doing that helps me find things a lot faster and allows me to categorize files (such as controllers) by functionality. My recommendation is to go with whatever works best for you. Anyone who says, “You’re doing it wrong!” should be ignored. Contrary to what some people think, there is no “one right way” to organize scripts and other files. As long as the scripts make it down to the client properly (you’ll likely minify and concatenate them anyway to reduce bandwidth and minimize HTTP calls), the way you organize them is completely up to you. Here’s what I ended up doing for this application: Animation code for some custom animations is located in the animations folder. In addition to AngularJS animations (which are defined using CSS in Content/animations.css), it also animates the initial customer data load using a 3rd party script called GreenSock. Controllers are located in the controllers folder. Some of the controllers are placed in subfolders based upon the their functionality while others are placed at the root of the controllers folder since they’re more generic:   The directives folder contains the custom directives created for the application. The filters folder contains the custom filters created for the application that filter city/state and product information. The partials folder contains partial views. This includes things like modal dialogs used in the application. The services folder contains AngularJS factories and services used for various purposes in the application. Most of the scripts in this folder provide data functionality. The views folder contains the different views used in the application. Like the controllers folder, the views are organized into subfolders based on their functionality:   Back-End Services The Customer Manager application (grab it from Github) provides two different options on the back-end including ASP.NET Web API and Node.js. The ASP.NET Web API back-end uses Entity Framework for data access and stores data in SQL Server (LocalDb). The other option on the back-end is Node.js, Express, and MongoDB.   Using the ASP.NET Web API Back-End To run the application using ASP.NET Web API/SQL Server back-end open the .sln file at the root of the project in Visual Studio 2012 or higher (the free Express 2013 for Web version is fine). Press F5 and a browser will automatically launch and display the application. Using the Node.js Back-End To run the application using the Node.js/MongoDB back-end follow these steps: In the CustomerManager directory execute 'npm install' to install Express, MongoDB and Mongoose (package.json). Load sample data into MongoDB by performing the following steps: Execute 'mongod' to start the MongoDB daemon Navigate to the CustomerManager directory (the one that has initMongoCustData.js in it) then execute 'mongo' to start the MongoDB shell Enter the following in the mongo shell to load the seed files that handle seeding the database with initial data: use custmgr load("initMongoCustData.js") load("initMongoSettingsData.js") load("initMongoStateData.js") Start the Node/Express server by navigating to the CustomerManager/server directory and executing 'node app.js' View the application at http://localhost:3000 in your browser. Key Features The Customer Manager application certainly doesn’t cover every feature provided by AngularJS (as mentioned the intent was to keep it as simple as possible) but does provide insight into several key areas: Using factories and services as re-useable data services (see the app/services folder) Creating custom directives (see the app/directives folder) Custom paging (see app/views/customers/customers.html and app/controllers/customers/customersController.js) Custom filters (see app/filters) Showing custom modal dialogs with a re-useable service (see app/services/modalService.js) Making Ajax calls using a factory (see app/services/customersService.js) Using Breeze to retrieve and work with data (see app/services/customersBreezeService.js). Switch the application to use the Breeze factory by opening app/services.config.js and changing the useBreeze property to true. Intercepting HTTP requests to display a custom overlay during Ajax calls (see app/directives/wcOverlay.js) Custom animations using the GreenSock library (see app/animations/listAnimations.js) Creating custom AngularJS animations using CSS (see Content/animations.css) JavaScript patterns for defining controllers, services/factories, directives, filters, and more (see any JavaScript file in the app folder) Card View and List View display of data (see app/views/customers/customers.html and app/controllers/customers/customersController.js) Using AngularJS validation functionality (see app/views/customerEdit.html, app/controllers/customerEditController.js, and app/directives/wcUnique.js) More… Conclusion I’ll be enhancing the application even more over time and welcome contributions as well. Tony Quinn contributed the initial Node.js/MongoDB code which is very cool to have as a back-end option. Access the standard application here and a version that has custom routing in it here. Additional information about the custom routing can be found in this post.

    Read the article

1 2  | Next Page >