w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Mongoose: Collection not populating when used as a ref in another document
Well, I figured out what the problem was. Kinda feeling like an idiot, but here it is. I had both the Card and the Deck schema defined in the same file since they were related and it made sense. At the end of the file, I had the following: module.exports = mongoose.model('Card', CardSchema); module.exports = mongoose.model('Deck', DeckSchema); Which meant that my Card schema was never being exposed because I wasn't thinking when I exported the models. I moved the Deck schema to a separate file, and now it all works. Stupid mistake, but now I know. And knowing is half the battle.

Categories : Node Js

mongoose model inheritance within javascript prototypal object
This turns out to be unrelated to javascript prototypes and completely due to how mongoose does Mixed Type Schemas: In order to tell mongoose the document has changed you need to markModified(field) example here: http://mongoosejs.com/docs/schematypes.html#mixed

Categories : Node Js

Is it possible to get the model from the document in mongoose?
//Assume you have a `user` variable that is an instance of the User model, //but this will work for any mongoose model instance var Model = user.constructor; //now you can do Model.find()....to run your query and this will work //on any collection //If you need the name of the model, it's user.constructor.modelName

Categories : Node Js

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

BackBone Model - > Collection -> Model -> Update - does not trigger change on root model
I found out how to do it, just listen to 'data' change and trigger 'change' futher ServerInfoModel = Backbone.BaseRelationalModel.extend({ url: function () { return "/examples/serverInfo.json" }, setup: function () { var self= this; this.get('data').on('change', function () { self.trigger("change"); }); }, relations: [ { type: Backbone.HasMany, key: 'data', relatedModel: 'Data', collectionType: 'DataCollection', reverseRelation: { key: 'id', includeInJSON: 'id' } } ] }); Data = Backbone.BaseRelationalModel.extend({ }); DataCollection = Backbone.Collection.extend({ model: Data });

Categories : Javascript

Collection name in Mongoose
So I'm fairly certain mongodb doesn't care about database name "blog" vs "blogs". However, do note that mongoose has the questionably-helpful feature of silently queueing up operations while the database connection is still not established and then firing them off if/when the database connection is ready. That could be causing your confusion. To test that theory, pass a callback to mongoose.connect and put a console.log in the callback so you know exactly when the connection is ready.

Categories : Node Js

How to use Document#update in Mongoose?
The Mongoose api is based on the underlying MongoDB query structure. In this case, "doc" refers to a criteria for matching certain documents that you want to update. The MongoDB docs explain this very clearly: http://docs.mongodb.org/manual/core/write-operations/#update So, let's say that you had a 'cars' collection, and you wanted to find all documents (all cars) that had 3 wheels, and increment that value so those cars had 4 wheels. In this case, "doc" is { wheels : 3 }, which returns all three-wheeled cars in the collection. Here is the basic query in the MongoDB shell: > db.cars.update( { wheels : 3 }, { $inc : { wheels : 1 } } ); In Mongoose, you can add additional parameters for options and a callback function, but that's the basic idea.

Categories : Mongodb

How to keep two read only collection synced with mongoose
My suggestion would be to insert into a new empty collection with a temporary name and then rename it to overwrite the existing collection atomically. You could also consider doing an upsert on each document that has been created or updated in the spreadsheet and then delete any deleted documents.

Categories : Database

Updating Mongoose Subdocument collection
As your UserSchema doesn't contain much information, it's probably simplest if you don't try to fake a join through Mongoose's population feature. Using MongoDB by itself, accomplishing this would be done with a single operation. Below, I'm just storing the "_id" field of some user document that I want to reference. > var userID = userdoc._id; > db.comments.update( { _id : commentID }, { $push : { likes : userID } } ); Doing this with Mongoose would require you to change your schema slightly: var CommentSchema = new Schema({ commentContent : String, commentPostTime : Number, likes : [ObjectId], likeCount: {type: Number, default:0} }) Then, you could just add the new user to the list of likes and increment the likeCount field with the following quer

Categories : Mongodb

Iterate through a Sorted Mongoose Collection
Getting your head around async programming in node.js is a bit of a pain if you're new to the concepts. Have a look at the last part of this link for some lessons to avoid. Basically if you write for(var i = 0; i < objects.length;i++) { var object = objects[i] db.save(object, function(err, result) { } } All the save operations are executed in parallel, not serially like you would expect in Java. Wrapping your head around this is the first step. You can use some libraries like step or async to help you with the orchestration of calls and iterations.

Categories : Javascript

mongoose save embedded document
Because story.lines is not an Array. You probably need to update the Schema to convert the lines to type Array in this way: var LineSchema = new Schema({ text: { type: String }, entered_at: { type: Date }, user: { id: { type: Schema.ObjectId, ref: 'Users' } } }); var StorySchema = new Schema({ title: { type: String, required: true }, users: { id: { type: Schema.ObjectId, ref: 'Users' }, creator: { type: Boolean } }, maxlines: { type: Number, default: '10' }, lines: [LineSchema], created_date: { type: Date, default: Date.now }, updated_date: { type:

Categories : Node Js

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

Populate with inherited document in Mongoose
Doh.. changing var componentSchema = new Schema({ name: String , desc: String }, { discriminatorKey : '_type' }) to var componentSchema = new Schema({ name: String , desc: String }, { collection : 'components', discriminatorKey : '_type' }) Fixes the issue. Not sure why.

Categories : Node Js

Mongoose: doesn't put _id to embedded document
When defining a schema you can specify options as a second parameter. Set _id to false to disable auto _id. var Embedded = new Schema({ some: String }, { _id: false }) See the docs.

Categories : Node Js

Mongoose.js unable to get an array from my document
console will always print the array with objects as [object object]. pages is actually an array of object, So you can specify an index to the pages array like this console.log(user[0].pages[0]); or if the pages array contain more than one element you want a regular for loop for (var i = 0; i<user[0].pages.length; i++) { // use i as an array index console.log(user[0].pages[i]); }

Categories : Json

Changing data in mongoose document
I'm assuming that the user variable is a Model object, and that what you're trying to achieve is to find a single user with a given username and code, and set the banned property of that user to be true. The first thing is that user.find will return an array of users, not just a single user, so you'll want to use user.findOne instead. user.findOne({ username: Username, code: Key}, function(err, userDoc) { if (err) { // TODO: Handle the error! } if (! userDoc) { res.json('nope'); } else { userDoc.banned = true; userDoc.save(function (err) { if (err) { // TODO: Handle the error! } res.json('yep'); }); } }) This queries the database for a single docu

Categories : Database

Python model inheritance and order of model declaration
Perfectionists look away!! This is a workaround (hack); the solution would be to solve the incorrect declaration order. WARNING: This is extremely daft. Concept: Imagine a namespace where anything can exist. Literally anything that is asked of it. Not the smartest thing usually but out-of-order declaration isn't smart either, so why not? The key problem of out-of-sequence classes is that dependent classes were being defined before their dependencies, the base classes. At that point of evaluation, the base classes are undefined resulting in a NameError. Wrapping each class in try except statements would take as much effort as rewriting the module anyway, so that can be dismissed out of hand. A more efficient (in terms of programmer time) means of suppressing NameError must be used. Th

Categories : Python

Backbone.js - extending a model(in collection) using parse method not getting the updated collection
That is because the response in done is not a Collection. It is just an object from the response.. Log c which is an updated collection c.done(function(data){ console.log(c); //Will be the updated collection }) Also listening to the event is a cleaner approach than using promised methods. initialize: function() { this.$el.html(this.template); this.c = collection; this.listenTo(this.c, 'sync', this.logCollection); this.c.fetch(); //fetching the data }, logCollection: function() { console.log(this.c); // This will log the collection }

Categories : Jquery

NodeJS Mongo - Mongoose - Dynamic collection name
Collection name logic is hard coded all over the Moongose codebase such that client side partitioning is just not possible as things stands now. My solution was to work directly with the mongo driver - https://github.com/mongodb/node-mongodb-native This proved great, the flexibility working with the driver directly allows for everything required and the Moongose overhead does not seem to add much in any case.

Categories : Node Js

Querying an array inside a mongoose document
You can use dot-separated paths in a query like so: User.find({'devices.deviceRegistrationId': deviceRegistrationId}). If that query doesn't match any documents, no user has that device. Note that mongo is smart enough to test all members of the devices array when given a query such as this. You can also add a user ID to your query conditions if you want to check a specific user.

Categories : Node Js

Mongoose update document Fail with findByIdAndUpdate
findByIdAndUpdate is a static method: var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks'); var lm = req.body; delete lm._id; landmarkModel.findByIdAndUpdate(req.body._id, lm, console.log); Note that landmarkModel accepts plain js objects. If you already have a mongoose object then it's best to use save instead: var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks'); landmarkModel.findById(req.body._id, function (err, lm) { if (err) return next(err); //adding data to schema here, like: lm.name = req.body.name; lm.save(console.log); });

Categories : Node Js

Mongoose - querying by comparing attributes of a document
collection.find({ $where : "this.a < this.b" }) This query is not performant. Or While inserting the document, insert a boolean true/false based on (a < b ) or ( b < a ) and query for that boolean.

Categories : Mongodb

how to find any document in database with an object id with mongoose?
Operations in MongoDB only always work on one collection. If you want to do a find on multiple collections, then you need to run multiple queries - one per collection. Of course, it's quite for Mongoose to implement a convenience function for that, but I don't think it has, or should, as it is against one of MongoDB's paradigms.

Categories : Node Js

Why would Mongoose be saving the same document multiple times?
So, I got it! I had a property in my schema named 'index': names: [{ sort: String, display: String, brief: String, nonLatin: String, personal: { type: Boolean, default: false }, index: { type: Boolean, default: true } }], index is used in Mongoose to indicate whether a document property should be indexed by MongoDB, and I was using it here as the name of a normal document property. Changing the name of the property to showInIndex fixed it. It was a foolish error, but I think that the effect it had is pretty surprising so this answer may prove useful to someone in the future. (Does anyone know why it caused this behavior instead of just throwing an error or something?)

Categories : Javascript

Easiest way to copy/clone a mongoose document instance?
Can you clarify what you mean by "copy/clone"? Are you going trying to create a duplicate document in the database? Or are you just trying to have two vars in your program that have duplicate data? If you just do: Model.findById(yourid).exec( function(err, doc) { var x = doc; Model.findById(yourid).exec( function(err, doc2) { var y = doc2; // right now, x.name and y.name are the same x.name = "name_x"; y.name = "name_y"; console.log(x.name); // prints "name_x" console.log(y.name); // prints "name_y" }); }); In this case, x and y will be two "copies" of the same document within your program. Alternatively, if you wanted to insert a new copy

Categories : Mongodb

Using Mongoose JS to get array of pointer values for document, and expand return
Mongoose provide you a feature population which exactly does the same thing you are looking for http://mongoosejs.com/docs/populate.html. In your case what you need to do is var mongoose = require('mongoose') , Schema = mongoose.Schema var tempSchema = Schema({ title : String, artifacts : [{ type: Schema.Types.ObjectId, ref: 'Artifacts' }] }); var artifactsSchema = Schema({ title : String, media : { player: String, source: String, } }); var tempModel = mongoose.model('Temp', tempSchema); var artifactsModel = mongoose.model('Artifacts', artifactsSchema); Now whenever artifacts documents gets created you need to push that in respective temp dcoument artifacts array as shown in mongoose documentation. You can retrive it like that tempModel .find(query) .pop

Categories : Node Js

Retrieve Backbone Collection from Model and keep it as a Collection
Instead of putting your collection into another model, you should put it in the according view: var ListView = new Backbone.View.extend({ initialize:function(){ this.Elements= new Elements(); // more stuff to go }, render:function(){ _.forEach(this.Elements, function(){ //Do rendering stuff of indivdual elements and get HTML }); //put HTML in the DOM } }); There is no need of a model containing a collection containing several models. Edit: And instead of putting your app into a Model, you should put it into a view.

Categories : Javascript

Mongoose document save fails with "TypeError: Cannot read property 'options' of undefined"
This was caused by my custom toObject and toJSON transform, which was removing properties I don't want serialized when returning JSON through my API. I didn't realize it also affected Mongoose's serialization to MongoDB. Edit: it can also be caused by trying to save a document with 'ref' properties which were not populated!

Categories : Node Js

Backbone fetch and reset model when model added to collection
First Ajax is Async . So you never know when the response comes back, so it is better to attach it to an event. ApvdtlView = Backbone.View.extend({ tagName: 'tr', initialize: function () { // This listens to the sync and change event and renders the item this.listenTo(this.model, 'change sync', this.render); this.template = _.template('<td> <%=itemid%> </td>' + '<td><%=qty%></td>'); this.model.fetch(); }, render: function () { this.$el.html(this.template(this.model.toJSON())); return this; } }); Next url property has to be set for the Model ApvdtlView as that is being fetched from the server. Next is you cannot hit this url from your domain urlRoot: 'https://raw.g

Categories : Backbone Js

Backbone JS add extended model to a collection of its inherited model type
The problem lies in appendItem method. You are calling it in this way: this.appendItem(new input.view({model: title}).el); But in this way you are passing as argument the view el, not the view itself, and so the view.model is undefined! You should refactor appendItem in this way: appendItem: function(view) { this.collection.add(view.model); $(this.container).append(view.el); }, And call it: this.appendItem(new editor.view({model: new editor.model()}));

Categories : Javascript

Mongoose Overwrite Model
mongoose.model must only be called once in your code. Try placing mongoose code outside the createServer callback, which is called every time request comes to the server, hence trying to re-register model.

Categories : Node Js

How to trigger a model update from another model in a collection in Backbone.js?
Actually you want to access other view from your current view and update it accordingly. I am afraid you need to create your own observer pattern. I mean publish and subscribe. var otherView = Backbone.View.extend({ initialize : function(){ observer.subscribe('your_custom_event'); }, your_custom_event : function(){ //update the view and it's model } }); winner: function() { this.model.set('wins', this.model.get('wins') + 1); this.model.save({wins: this.model.get('wins')}); observer.publish('your_custom_event', arguments); } You can get very good available patterns from the web easily those are compatible with backbone.

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

Mongoose Model alias error
When you call mongoose.model(...), the mongoose object is getting passed into the model function as this. When you call the function through your alias, this will be set to global instead of mongoose. If you really wanted to do this you'd have to do something like: var Model = mongoose.model.bind(mongoose); That way, mongoose gets passed into the function no matter how you call Model.

Categories : Node Js

Returning objects from mongoose model
In findUser you don't seem to be providing a place for that callback to go. The mongoose query itself also returns the document(s or error) to a callback to be handled. If you wanted to modify your findUser to fit with how you seem to be using it: exports.findUser = function(nameIn,callback){ User.find({name: nameIn}, function(err,user) { if (err) throw err; callback(user) }); )}; The results of mongoose's query (successful or not) are handed to the function in the arguments of the query (as a callback), which is in line with the asynchronous nature of Node. The other generally accepted methods of handling Node's non-blocking I/O are events and streams, with methods like promises being viable if somewhat controversial. Mongoose itself uses callbacks in its guides, b

Categories : Node Js

Call require on mongoose model more than once
I have run into this issue as well. Something you can do is wrap the schema definition in a try catch Replace this line var User = mongoose.model('User', UserSchema); with: var User; try { User = mongoose.model('User', UserSchema); } catch(e) { User = mongoose.model('User'); } Not sure if its the best way but it will work.

Categories : Node Js

Mongoose include model with dependencies
If you want to define an array of references, you should use the following definition: ResourceSchema = new Schema({ "comment": [{type : Schema.ObjectId, ref : 'Comment'}] }); The way you defined comments is used to define an array of subdocuments (see mongoose API docs). So, you should use it only if you want to store all your comments directly inside of the parent document. In this case Comments schema should be already defined, or required from another module.

Categories : Node Js

How to correctly jsonify a mongoose model with a birthday?
The problem is in the way your date gets created. I suggest you use dates in UTC-time for such data as birthdays, which would allow you to use UTC-times throughout the system. You can either: set the date in UTC in the constructor, supplying to it a string in UTC: new Date('1986-09-14T00:00:00.000Z'); use new Date(Date.UTC(year, month, day, 0, 0, 0)); to create a Date-object from an integer year, month and day. So, the answer is: you should store UTC date in birthday field when you create/update the model.

Categories : Json

How to sort nested Datas on a Mongoose Model?
Call toObject on your mongoose model instance to turn it into a plain object you can manipulate: var doc = MyDoc.toObject(); doc.Members.sort(function(a, b) { return b.points - a.points; });

Categories : Javascript

Mongoose Model.count() does not run callback as documented
Make sure you're connecting to the database first. Mongoose will just queue up the count query until you connect otherwise. See the fourth question of the FAQ.

Categories : Node Js



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