w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?
Express session is stored as separate storage and has limitations to what can be stored there. It cannot store prototype data (methods). Look at it more like key<>value storage. Reasons for this is that session can be stored anywhere (pretty much), such as: process memory; databases (mongodb); redis; etc. Because of this, once you put anything in session object and request is finished, express will take session data, parse it and stick into session store just as pure object. By default it is process memory, but as mentioned before - can be any other storages. So when next http request happens, session middleware will try to restore session using cookie (if it is used) data in request headers, and will ask session storage to provide data back. As it is already formatted - it will n

Categories : Node Js

Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.

Categories : Node Js

How to detect the difference between a change made by a user and a change made programmatically?
If you just change the value with el.value = x, the change event is not triggered. For example, this won't log anything to the console: var el = document.getElementById('el') el.onchange = function(){ console.log('changed'); }; el.value = 'asasassasa'; So, if you're seeing it's being triggered twice, it's either because: You're manually triggering it with el.onchange(). In this case, just remove the this call. Or: The event handler is bound to the element more than once. You have to locate where that's happening.

Categories : Javascript

Mongoose Schema with ObjectId
Are Posts a collection type in your system? If so : var userSchema = new Schema({ twittername: String, twitterID: Number, votedPosts: [{type: Schemas.Types.ObjectId , ref : 'Posts'}] }); Where 'Posts' is the name of your defined Posts model. See http://mongoosejs.com/docs/populate.html

Categories : Mongodb

Referencing another schema in Mongoose
It sounds like the populate method is what your looking for. First make small change to your post schema: var postSchema = new Schema({ name: String, postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, dateCreated: Date, comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}], }); Then make your model: var Post = mongoose.model('Post', postSchema); Then, when you make your query, you can populate references like this: Post.findOne({_id: 123}) .populate('postedBy') .exec(function(err, post) { // do stuff with post });

Categories : Javascript

getting schema attributes from Mongoose Model
Yes, it is possible. Each schema has a paths property, that looks somewhat like this (this is an example of my code): paths: { number: [Object], 'name.first': [Object], 'name.last': [Object], ssn: [Object], birthday: [Object], 'job.company': [Object], 'job.position': [Object], 'address.city': [Object], 'address.state': [Object], 'address.country': [Object], 'address.street': [Object], 'address.number': [Object], 'address.zip': [Object], email: [Object], phones: [Object], tags: [Object], createdBy: [Object], createdAt: [Object], updatedBy: [Object], updatedAt: [Object], meta: [Object], _id: [Object], __v: [Object] } You can access this through an model too. It's under Model.schema.paths.

Categories : Mongodb

Using 'generic' virtual for mongoose schema
For backbone, "id" is it's default idAttribute name, so just don't add any code there and everything will work as intended. For mongoose, the answer boils down to "it's complicated", but the main points are: By default mongoose will give each schema a virtual called "id" which will be the document's _id as a string However, by default .toJSON doesn't include virtuals, so when you send a mongoose document to backbone in the browser, it gets just "_id" and not "id" to quickly get a JSON representation including the virtuals, use myModelInstance.toJSON({virtuals: true}). You'll get both "_id" and "id" You need to read up on the transform options for toObject and toJSON to get a full picture of what you can do and how, but the gist is (based on examples straight from the docs) // specif

Categories : Node Js

Adding 'virtual' variables to a mongoose schema?
This is perfectly possible in mongoose. Check this example, taken from their documentation: var personSchema = new Schema({ name: { first: String, last: String } }); personSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); console.log('%s is insane', bad.name.full); // Walter White is insane In the above example, the property would not have a setter. To have a setter for this virtual, do this: personSchema.virtual('name.full').get(function () { return this.name.full; }).set(function(name) { var split = name.split(' '); this.name.first = split[0]; this.name.last = split[1]; }); Documentation

Categories : Node Js

How to properly handle mongoose schema migrations?
I am doing migration like this; Let say I have db called Item. On any schema changes, I create anotherdb called ItemTemp and copy all data to ItemTemp. I executed schema change scenario on ItemTemp db. If everything goes well, I schedule db down time. I copy Item to ItemTemp again execute schema change migration and copy all data to Item db. Hope it helps

Categories : Mongodb

Create a schema in mongoose nodejs for one record only
Yes, this is possible without anything special really other than only put 1 document into that collection. I would just leave your default set of configuration settings as a simple javascript object in code and if you find a configuration record in mongo, just use that to override the defaults via _.defaults or similar. For what it's worth, more commonly identifying the blog admin would be stored on the user record, not in a blog configuration object (user.isAdmin = true for a simple case), but either way will work.

Categories : Database

why mocha assertion fails on mongoose.Schema.objectId?
So mongodb ObjectIds in javascript are sadly frustrating in this regard. They are distinct objects resulting in obj1 === obj2 evaluating to false even though the value they represent is identical. There are 3 options: Convert to strings before comparing. I use this a lot because it's so frustrating otherwise. Use the .equals() method they provide: assert.ok(model.organizationId.equals(objId)) Write a custom comparison function that can take null, ObjectIds, or Strings and do the right thing (I've also done this)

Categories : Node Js

Why doesn't my Mongoose schema method "see" my required object?
I believe the issue is that you've created a circular dependency. Story executes require(config.models) which requires Story again inside index.js. Rather than storing a string and requireing it everywhere, try storing the models directly in config.models: config.js module.exports = { test: 'test', models: require(__dirname + '/models') };

Categories : Node Js

Two database queries in Mongoose with Express
Yes, there are many many flow control libraries to solve the deeply nested callback problem. I recommend async or nimble, but promises is another popular pattern that solves this problem. The basic progression as you add code and it gets longer and more deeply nested over time is: deal with 1 or 2 nesting levels with small amounts of code. It's not that bad. Extract things to top-level named functions and call them (most node.js core code tries not to get beyond this point) use a library (either custom API or based on the promises pattern) There is a long list of flow control modules on the node wiki. You could also search npm

Categories : Javascript

Variable inside $http not reflecting change outside block
I don't think you can directly insert XML like you can JSON without some sort of parser. Check out this question for handling XML in AngularJS: How to handle XML services in AngularJS? Specifically check out these modules/plugins to help: https://github.com/johngeorgewright/angular-xml https://code.google.com/p/jquery-xml2json-plugin/

Categories : Http

DIfference between sub docs and population in Mongoose and doubts about database schema
In answer to part one, the difference is that in a Document-Subdocument scenario the subdocument is stored with the document (as a child document, accessible through the use of dot notation). In the Mongoose populate scenario, a reference is held to a document in another collection. When you tell mongoose to populate what it does is make another query to MongoDB to get this 'subdocument'. The main difference I see is that with the mongoose populate method you cannot query for documents using the 'subdocument' properties, whereas you can with the embedded subdocument model. Edit, subdocument example So in MongoDB you can store the data as nested subdocuments like so: { _id: acbdbd, "property": "value", "subdocumentproperty" : { "param1": 1, "param2": 2

Categories : Mongodb

Saving mixed schema in mongoose (markModified doesn't seem to work)
The save method is asynchronous, which means you can't be sure it has finished its work the way you write your code now. Use callbacks: results[0].save( function(error){ if (error){ // augh! }else{ console.log(results[0]); // <- yay! the document is definitely saved here // ... } }); //console.log(results[0]); // <- no, we can't be sure results[0] is already saved in this line

Categories : Mongodb

Inserting Object ID's into array in existing Mongoose schema with Node.js
Keep the category names you want to search for in an array { categories: ["cat1", "cat2"] } then you can add an index to it and do a $in query. the current schema is not very good because you cannot look for the category in a single query but need to resolve all the "categories" links first.

Categories : Javascript

Upvote and Downvote with Backbone, Express and Mongoose
There're many things that can be improved: First, you client-side code is a low hanging fruit for an attacker - you do an atomic operation (upvote/downvote) with two requests, and the first request not only sends vote type but also sends total number of votes: this.set ({votetype : 1 }, {votes : this.get('votes') + 1}); this.save(); // btw this looks broken, the second argument for `set` is options, so // if you want to set votes, you should move them to the first argument: this.set ({votetype : 1, votes : this.get('votes') + 1}); But, how your application will respond if the attacker will send 100 or even 1000 votes? This operation should be atomic, and you should increment votes on the server when you make POST request to the /upvote endpoint. Second, you don't really need to stor

Categories : Node Js

Scaffolding with node.js, express and mongoose like grails?
There isn't any native way to do that, but you can use the yeoman project to generate some scaffolding based on the templates they have available. They have a node/express generator.

Categories : Node Js

node + express + mongoose query authentification
YEah robert klep was right on the money, After i seearched the mongoose Documentation and the mongodb docs as well, it became clear that queries return a mongo document object, in terms should be converted to the same object or variable types for opperands to work.

Categories : Javascript

What's the proper way to handle mongoose connections with express.js?
If you connected to the database already, the once event won't fire again. The database was already connected for the entire NodeJs process when it was globally connected (outside of the function). The call to mongoose.connect('mongodb://localhost/test'); makes the connection and opens it. So, instead of opening it on each function call (which would be an inefficient way to interact with MongoDB) connect right away when the NodeJs app is started, and consider that there will be a period where the connection may not be available (as it's async), or don't start the app (listen) until the connection is complete (or with a timeout). With Mongoose, until the connection is made, all commands are buffered (but that may not be the behavior you want). You can use the open event if you want to kn

Categories : Javascript

Mongoose ignoring part of object unless defined as Schema.Types.Mixed
The type property of attr is likely tripping up Mongoose to thinking attr is a string instead of an embedded object. Use a more explicit definition for the property, like this: attr: appearance: String aroma: String flavor: String from: String grade: String lineage: String name: String overall: String packaging: String pickupdate: String price: String reason: String story: String type: type: String

Categories : Javascript

Input field validation in Node.js Express.js Mongoose
If you are just starting the study Express, then play with express-validator with this micro tutorial or use Mongo's build in validators

Categories : Node Js

How Express/Mongoose populate data to HTML select tag
I don't quite understand your question completely since the question has many parts but it seems like you're trying to avoid asynchronous paradigm. You can wait for mongoose objects to be populated before rendering them with template. You can either force async behavior in node https://github.com/caolan/async#parallel async.parallel([ function(callback){ CreatorModel.find({}).exec(function(err, crts) { creators = crts; callback(creators); }); } ], // optional callback function(err, creators){ res.render('tasks/create-form', { creators: creators, assignees: assignees }); } Or use QueryStream to pipe it to res.render http://mongoosejs.com/docs/api.html#querystream_QueryStream Later on, you c

Categories : Node Js

Change value of dropdown to null if specific change is made to radio button, but not just any change
Use click function and use class as the radio box selector. jQuery(document).ready(function($){ $('.myradiobox').click(function(){ var radioVal = this.val(); if(radioVal == 5 || radioVal == 4) { radioVal == 'NULL'; } $('select[name="item_meta[106]"]').val(radioVal); }) })

Categories : Javascript

Can't add keys with dots (key paths) to a Mongoose field with type: Schema.Types.Mixed
Yes, it is. Valid JSON doesn't have dots as far as I know. What you are supposed to do is this: { "character": { "treasure_chests": 1 } } Here is an example: JSON Schema example

Categories : Json

Mongoose Query Data in Express.js Node.js ,get the wrong result
(not sure if this is causing the problem, but it seems worth mentioning anyway) Here, you're passing req.cookies.session, which is an object: userModel.checkSession(req.cookies.session, ...); But in checkSession, you're assuming it's an id: UserModel.prototype.checkSession = function(sessionID, callback) { sessionMongooseModel.findOne({sessionID:sessionID}, ...); Just out of curiosity: any reason why you're not using one of the existing MongoDB-backed session stores for Express (like this one)? Also, Mongoose has it's own way of adding class methods to models, using statics.

Categories : Node Js

Unable to access data from Mongodb via express/mongoose/angularjs
You likely will want to add a route specifically for the "news": app.get('/news', function(req, res, next){ News. find(). exec(function(err, nws){ if(err) { res.writeHead(500, err.message) } else { res.send(nws); } }); }); Right now, you've got it returning the basics of a web page (res.render('index', { title: 'static Express' });) and then the response from the find call. Angular won't accept that as a result, and it explains why you're seeing the DOCTYPE in the response. And then call it from your Angular code: var News = $resource('/news');

Categories : Node Js

Import schema file into SQL server express database?
If you are talking about OpenFire ala Ignite RealTime you need to follow the instruction for Microsoft SQL Server (not MySQL). The reference page instructions for Microsoft SQL Server has the following SQL Server JDBC Drivers Openfire includes the Free TDS JDBC driver, which is the recommended way to connect to SQL Server databases. To connect to SQL Server, simply use the following values in the Openfire web-based setup tool: driver -- net.sourceforge.jtds.jdbc.Driver server -- jdbc:jtds:sqlserver://[host-name]:[port-number]/[database-name];appName=jive where [host-name] is the host name or IP address of your database server, and [port-number] is the port that SQLServer is listening on (normally 1433) and [database-name] is the name of the database (this parameter is optional). Setup

Categories : SQL

How to change sub document after finding with mongoose
Sorry, I've resolved myself. The problem is the order of declarating Schemas. It worked if I tried this change. /* first, children's schema */ var ChildSchema = new Schema({ name: String, }, {_id: false}); /* seconds, parent's schema */ var UserSchema = new Schema({ name: String, children: [ChildSchema], });

Categories : Javascript

How to change URL links that were made by WordPress?
I believe what you're looking for can be found in the admin panel. In the admin panel (http://www.your-wordpress-site.com/wp-admin), go to Settings > Permalinks

Categories : PHP

How to detect value change that is made dynamically
Try this: $("#total_amt").on("input", function() { alert("Handler for .change() called."); }); this is HTML5 thing though won't work with the modern browsers, for other browsers var lastValue = ''; $("#total_amt").on('change keyup paste', function() { if ($(this).val() != lastValue) { lastValue = $(this).val(); calert("Handler for .change() called."); } });

Categories : Javascript

Passport-Local Mongoose - Change password?
Looking at the source there is a function that is added to the schema called setPassword. I believe that after authenticating you can call it to change the password for the user. schema.methods.setPassword = function (password, cb) { if (!password) { return cb(new BadRequestError(options.missingPasswordError)); } var self = this; crypto.randomBytes(options.saltlen, function(err, buf) { if (err) { return cb(err); } var salt = buf.toString('hex'); crypto.pbkdf2(password, salt, options.iterations, options.keylen, function(err, hashRaw) { if (err) { return cb(err); } self.set(options.hashField, new Buffer(hashRaw, 'binary').toString('hex')); self.set(options

Categories : Node Js

How to make a contenteditable div reversible after change made with js?
What about adding a keyup event handler that will keep track of the current text after every keyup. You can then trap crtl + z and revert back to the previous content if you detect that crtl + z have been pressed. You could potentially keep revisions in an array to support a series of ctrl + z operations.

Categories : HTML

Dataframe does not remember change made by a function
Your syntax is wrong if your purpose is to update data1. You should use updateRow <- function(rIndex) { data1[rIndex, 4] <- 1 return(data1) } data1<-updateRow(4) This should do it. It will update row 4 and column 4 and set the value to 1. If you want to skip the last assignment you can define the function as updateRow <- function(rIndex) { data1[rIndex, 4] <<- 1 } updateRow(4) which will also update row 4 and column 4 to the value 1. This is the same solution as dayne has in his answer.

Categories : R

Buttons that need to change their .innerHTML but they are made in a loop so they end up having the same id
When you are looping through creating each button, create a counter variable, or use the variable from the for loop, and each loop increment it by 1 and append that to the ID. for(var i = 0; i < some_number; i++){ var ID = "myButton"+i; //Other code }

Categories : Javascript

Rails - Do we need to restart server everytime a change is made?
You should not be using the production mode as a "development" mode. If you are making changes regularly, you should test on development mode and then if no bugs are found, you should push your code to your production environment.

Categories : Ruby On Rails

In a "shared" git repository, how do see what user made what change in a git status?
Short answer: No. Git only knows / is aware of the fact that the files in your working copy have changed; it has no knowledge of the working copy beyond that. Also, that's probably a really bad development model to be using.

Categories : GIT

Web API change schema names
You can use this attribute on your class(es) to customize the namespace: [DataContract(Namespace="http://example.com/namespace")] I don't think any namespace is included in JSON by default so this attribute won't affect that.

Categories : Asp Net Web Api

Change colors in a complex animation made of bitmaps/group
You need to define your matrix array before you instantiate the ColorMatrixFilter object. Also, ColorMatrixFilter expects a one dimensional array. See documentation which recommends a syntax using concat which seems to do the trick. Try updating your code with the following: // Matrix should be a one dimensional array var colorMatrix:Array = new Array(); colorMatrix = colorMatrix.concat([0, 0, 1, 0, 0]), colorMatrix = colorMatrix.concat([0, 1, 0, 0, 0]), colorMatrix = colorMatrix.concat([1, 0, 0, 0, 0]), colorMatrix = colorMatrix.concat([0, 0, 0, 1, 0]); // Matrix needs to be defined before it's added to the ColorMatrixFilter var colorFilter:ColorMatrixFilter = new ColorMatrixFilter(colorMatrix);

Categories : Actionscript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.