Found the answer. The problem is that I push mongoose Model instances into the array. But only plain objects are allowed.
javascript,node.js,callback,mongoose
If you make that the first parameter instead, you can use .bind(). token.save(saveCallBack.bind(null, email_address)); var saveCallBack = function(email_address, err, model){}; ...
You're declaring an instance method (meant to be called on instances of the User model/class) but you're calling it as a class method (a static method in Mongoose parlance). Here's a small demonstration: var mongoose = require('mongoose'); var testSchema = new mongoose.Schema({ test : String }); testSchema.methods.myFunc = function() {...
I wasn't able to reproduce that error message, but as you've seen, Mongoose will only update fields defined in the schema. However, you can override that default behavior by including the strict: false option: groupsModel.update( {_id: group._id}, {$unset: {"moderators": ""}, $set:{"admins": newAdmins}}, {strict: false} ) ...
This is because you have have a Mongoose model (assuming that you are using mongoose because of the __v attribute for versioning) that is freezed (prevents atributes form being deleted), one thing you can do is: //remove the version key '__v' var elements = elements.map(function (element) { element = element.toJSON();...
javascript,node.js,mongodb,express,mongoose
Replace in schema.js var Int = mongoose.model('Int', InterestSchema); and in server.js add var Int = mongoose.model('Int'); It will work now. ADD var mongoose = require('mongoose'); IN schema.js And the schemas should match....
javascript,node.js,mongodb,mongoose
Since the address field is not required by Mongoose when you retrieve the Model from the database the field just won't be defined. Thus you won't be able to add an address field. You should check to see if it exists if(member.address === undefined){ member.address.push(new_address); } else{ member.address = [new_address];...
The issue was that post hooks require you to use the doc to access the object, as also explained and answered in Why is the "this" keyword different in a mongoose pre-save hook versus a post-save hook?.
Mongoose inserts the value inmediatly. The problem is that you are not using it´s callback. Try to code this way: //There is the definition Customer.create(YOURDATA, function (err, obj) { if (err) { //This will be executed if create is going bad. return handleError(res, err); } //This code will be executed...
angularjs,mongodb,api,mongoose
Solved it using: $http.put('/api/users/'+User._id, {'projects': User.projects}); and in my update method: _.extend(user, req.body); instead of _.merge(user, req.body);...
Unfortunately you can't. When you execute a function, you get whatever you return from it. If you return nothing you get undefined by default. Instead of having your readability based on getting the user, you should have it based on what you're going to do with it once you've gotten...
It seems that you confuse between populate and select. populate is to be used when you have a reference to an external schema like owner : { type: Schema.ObjectId, ref: 'User' }. If you want to display owner fields, then you need to call populate('owner') to load the user. What...
The "query" form of populate doesn't take an array as argument, but an object: // `model` can be left out as Mongoose will look that up in the schema var populateQuery = { path : 'stamps', select : selectQuery }; ...
node.js,mongoose,find,middleware
The issue ended up being the order of the items. Apparently you must define the model after setting up the find hooks. This is not required for the save and update hooks though. // define the schema for our recs model var recSchema = mongoose.Schema({ dis: String, // rec display...
Since I'm sensing dangerously bad advice issuing from people telling you to .find() the data then .save() it I'll explain the basic case of "flattening" the data in order to avoid the nested array issue. Nested arrays suffer from a problem that the positional $ operator you would need to...
You can get models by name: var mongoose = require('mongoose'); app.get('/:trial', function(req, res){ var trial = req.params.trial; mongoose.Model(trial).find(function(err, records) { if (err) { // Return when we end the response here... return res.send(err); } res.json(records); // returns all trial records in JSON format }); }); Depending on circumstances, I would...
angularjs,node.js,mongoose,mean-stack
Finally fixed it, needed these changes: <div class="controls" ng-repeat="(key, module) in project.website.data.modules"> <label for="{{key}}"> module: {{key}} = {{module.active}}</label> <input type="checkbox" name="modules" value="{{key}}" data-ng-model="module.active" id="{{key}}"><br> <div class="features_settings" ng-repeat="(key2, feature) in module.data track by $index"> <label for="{{key2}}">Feature: {{key2}} , value = {{module.data[key2]}}</label> <input type="text"...
node.js,mongodb,mongoose,mean-stack
Answer provided by laggingreflex: exports.updateAnswer = function(req, res) { var ansId = req.params.aid; var result; Poll.findById(req.params.id,function(err, poll){ if(err) { return handleError(res, err); } poll.answers.forEach(function(answer){ if(ansId == answer._id) result = answer; }) var updated = _.merge(result, req.body); poll.markModified('answers'); poll.save(function (err) { // <== change here if (err) { return handleError(res, err);...
angularjs,node.js,express,mongoose,passport.js
So apparently the problem is that HTML defaults to finding an index.html file in any folder within the root. When I change the html file to something else like abc.html the problem is solved. Seems like a bug to me.
Group.find({program: {$in: [...]}}) .lean() .distinct('_id') db.collection.distinct(field, query) Finds the distinct values for a specified field across a single collection and returns the results in an array. Read more....
node.js,mongodb,express,mongoose,ejs
My guess for the "headers already sent" error is that your // or just latest code is running even when one of the above if statements runs. If that's the case then you'll surely be making multiple calls to res.render or res.send. Try this: router.get('/', function(req, res, next) { /*...
arrays,node.js,mongodb,mongoose,schema
You can use the distinct function to get the unique values across all category array fields of all documents: Article.distinct('category', function(err, categories) { // categories is an array of the unique category values }); Put an index on category for best performance....
From what I see in your terminal, I think your installation for mongoose is successful. And you are staring your application using nodemon but I think that is not installed as you are getting an error nodemon: command not found. So first you will need to install nodemon using, npm...
javascript,mongodb,express,mongoose,mean
You will need to test the error returned from the save method to see if it was thrown for a duplicative username. app.post('/authenticate', function(req, res) { var user = new User({ username: req.body.username }); user.save(function(err) { if (err) { if (err.name === 'MongoError' && err.code === 11000) { // Duplicate...
javascript,node.js,mongodb,mongoose
Thank you both for your input. It's truly appreciated. I managed to solve this an easier way which now I come to think of it is pretty obvious - but hey we live and learn. Basically, my 'userListings' model field was an array of Object Id's and I wanted to...
javascript,mongodb,mongoose,sails.js
I want to give the different privileges for each of user Super admin can access whole DB. Admin can access the data relate to that field User can access the data related to the user. What you need is primarily a document-level access control where a user can access...
node.js,mongodb,express,mongoose
While I'm sure there are other ways to do this, I've accomplish this in the past by populating the docs resulting from the aggregate method. Here's an example: Order.aggregate([ { $group: { _id: "$location", location: { $first: "$location" }, totalSales: { $sum: "$subtotal" } } } ]).exec(function(err, docs) { Order.populate(docs,...
javascript,node.js,mongodb,indexing,mongoose
I think, what you are looking for is the ability to join tables of data and perform a query against the sum of that data. That is something you need a relational database for, which MongoDB isn't. So I recommend you change your approach in how you would like to...
If you want mongodb to handle the query internally you could use the aggregation framework. In mongodb it looks like: db.users.aggregate( [{ $group: { _id: '$firstName', // similar to SQL group by, a field value for '_id' will be returned with the firstName values count: {$sum: 1} // creates a...
As I grew to suspect, it was due to it being an instance of a Mongoose document, as opposed to just a normal Javascript object. I was able to find the solution here: How do you turn a Mongoose document into a plain object? And adding .lean() into the query...
javascript,arrays,node.js,mongodb,mongoose
Try adding the other property in your validation by using this.pending_elements and comparing the arrays using the lodash library's _.isEqual() and _.sortBy() methods: var schemaInterest = new schema({ active_elements: { type: [String] }, pending_elements: { type: [String] } }); schemaInterest.path('active_elements').validate(function (v) { return _.isEqual(_.sortBy(v), _.sortBy(this.pending_elements)) }, 'my error type'); --...
Use the $push or other array update operators to add elements to an array. For details, refer http://docs.mongodb.org/manual/reference/operator/update/push/#up._S_push
javascript,node.js,mongodb,mongoose,passport.js
passport.use('local-signup', ... function(req, email, password, done) { The function expect three arguments email, password,done. change the callback function to function( email, password, done) { ...
angularjs,node.js,express,mongoose
You can also refactor out the database access bit in another method (probably in a different module - userController), which will make your code more readable. This doesn't qualify as an answer but putting all this in comment didn't look ok. exports.list = function (req, res) { if (hasRole('admin')) {...
angularjs,node.js,mongodb,mongoose,mongolab
I believe the error comes from the constant create/close of the mongo connection. To sustain a single connection over multiple endpoints: var Portfolio = require("../models/Portfolio") var Profile = require("../models/Profile") var db = mongoose.connect(config.server.db) db.connection.once("connected", function() { api.get("/profiles", function(req, res) { ... }); api.get("/portfolios", function(req, res) { ... }); }); You...
use mongoose type Mixed new Schema({ unique: Number, total: Number, hits: {} } Mixed An "anything goes" SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through Schema.Types.Mixed or by passing an empty object literal. The following are equivalent: var Person =...
javascript,node.js,mongodb,express,mongoose
This error could be happening because you're requiring Member model before Semester in app.js, this is because Semester model and schema not exist when './models/member' is required Try to change the order in app.js to: // MODELS require('./models/semester'); require('./models/member'); To avoid this situation you could require the model from the...
node.js,mongodb,mongoose,express-session,connect-mongo
You are saving your session object as plain text. because of that you cannot search as an object. Ensure that the schema of the "father" collection have the session field as type '{}' (Object) like: Father = {session: { type: {} }} If it not work, you can try the...
It's quite hard to say what's "the right way" to be honest, as this is most likely case by case depending on your application queries and architecture. I have seen some people do as you designed above; Solving many-to-many relationships by using reference in both collection. This would work for...
angularjs,node.js,mongodb,mongoose
GET requests queries are strings, so if you send this: www.mysite.com/?data=1&weightTotal=5 You will get this (strings and not numbers): {data: "1", weightTotal: "5"} In order to use the data you can parse it somehow, for example: req.query.weightTotal = JSON.parse(req.query.weightTotal); or if it's just a number, a faster parse is: req.query.weightTotal...
Most likely your first query won't work because MongoDB is expecting that _id is an ObjectId, and not a string (which req.params.id probably is): var ObjectId = require('mongoose').Types.ObjectId; exports.getUser = function (req, res) { var id = req.params.id; var $or = [ { username : id } ]; // Does...
One of oldArea or newArea must not be a number. If you add a number to something like undefined the result is NaN. var n = 5; n = n + undefined; // n is now NaN Interestingly, typeof NaN is 'number' which can be confusing as its whole purpose...
You can use aggregation db.collectionName.aggregate( [ { "$group": { "_id":null, "Artist": { "$push":"$asset.attributes.Artist" }, "Duration": { "$push":"$asset.attributes.Duration" } } }, { "$project": { "_id":0,"Artist":1,"Duration": 1 }} ] ) Edit As per new edited question you can do following aggregation to get the result db.collectionName.aggregate({ "$group": { "_id": null, "data": {...
In a NoSQL database everything is document oriented so you wouldn't typically do what you are trying to do. You will need to manage the "foreign key" relationship yourself, in code.
The getIndexes output shows that the index on qname wasn't created as a unique index. Mongoose doesn't alter an existing index, so you'll have to manually drop the index and then restart your app so that Mongoose can re-create it as unique. In the shell: db.restos.dropIndex('qname_1') ...
node.js,mongodb,mongoose,passport.js
It's because the document object you get back from mongoose doesn't access the properties directly. It uses the prototype chain hence hasOwnProperty returning false (I am simplifying this greatly). You can do one of two things: use toObject() to convert it to a plain object and then your checks will...
node.js,mongodb,mongoose,mongoose-populate
In Mongoose instance methods, this is the document instance the method is being called on, so you can do this as: MainSchema.methods = { retrieveChilds: function(callback) { this.deepPopulate('childs.subject.data', callback); }, }; Then to call it: main.retrieveChilds(function(err, _main) { // _main is the same doc instance as main and is populated....
node.js,mongodb,mongoose,openshift
On OpenShift, when you find or findOne a model that has a required reference to another entity, that field will not be automatically filled in. Thus, when save is called, the field will be missing. Change var query = List.findOne({ owner: userId, "_id": listId }); to var query = List.findOne({...
https://github.com/Automattic/mongoose/issues/3020 If anyone else is having this issue. I found this bug report that can explain the cause of the problem, it is related to how you install the new mongoose 4 apparently....
angularjs,node.js,mongodb,express,mongoose
According to the mongoose documentation of Subdocuments says: Sub-documents are docs with schemas of their own which are elements of a parents document array And in your schema you provided: guitarParts is not an array, it is an object and a guitarPart is not array it is an object too....
javascript,json,node.js,mongodb,mongoose
Use async module to do this. The function you need is async.eachSeries async.eachSeries(obj.data.categories, function(_cat, cb){ var newCat = {...}; Category.findOneAndUpdate({name:_cat.name},newCat,{upsert: true}, function(err,cat) { if(cat.children) { async.eachSeries(cat.children, function(_cat2, cb2){ // the code like above with cb2() }, cb); } else { cb() } }); }); ...
You can define a default with a function: var minuteFromNow = function(){ var timeObject = new Date(); timeObject.setTime(timeObject.getTime() + 1000 * 60); return timeObject; }; new Schema({ date: { type: Date, default: minuteFromNow } }) -- EDIT -- You can also use the momentjs library which has got some fantastic...
You need to convert the string _id to a valid Mongodb ID var mongo = require('mongodb'), BSON = mongo.BSONPure, groupid = new BSON.ObjectID(req.headers['groupid']); Cloud.find({'_id': groupid}).exec(function(err, data) { if(err){ res.status(404); res.json('group not found'); } else { // Do Stuff } }); If you use Mongoose you can convert the string to...
You can test multiple conditions at the same time in Mongoose. This should work for you. Session.findOne({ id: req.body.sessionId, user: req.body.userId }) .remove() .exec(); ...
node.js,mongoose,promise,bluebird
It seems you're not using Bluebird, but mongoose promises (mpromise), which don't have a .catch method. You can fix that by using user.saveAsync().then(…), as you've promisified the User model using Promise.resolve(user.save()).then(…) to cast the mongoose promise into a Bluebird one ...
node.js,mongodb,express,mongoose
Basically, you could use any solution for async control flow management like async or promises (see laggingreflex's answer for details), but I would recommend you to use specialized Mongoose methods to populate the whole array in one MongoDB query. The most straightforward solution is to use Query#populate method to get...
node.js,mongodb,callback,mongoose
When you don't pass a done argument to your test callback, mocha doesn't wait for its completion, but it still executes it. You did: it('should allow delete of the user created', function () { // your test }); So, that's why your user data is being deleted, but you can't...
node.js,mongodb,mongoose,schema
You can try this: objectModel.find({ 'members.user_id' : {'$in' : ['asdf123lkd', 'asdf1223']} }, function(err, data) { console.log(err,data); }) ...
According to the above link If field is not present then unwind will throw an error No, it don't: If a value in the field specified by the field path is not an array, db.collection.aggregate() generates an error. If you specify a path for a field that does not...
javascript,mongodb,express,mongoose,ejs
It looks like you are returning an array, but the correct variable is not being set in the object passed to render Give this a try (this should get the 1st course in the array): app.get('/yay', function (req, res, next){ Upload.find({}, function (err, courses) { res.render('./pages/yay.ejs', { happy: courses[0].title });...
First of all, a good understanding of what the map function is: Map takes a set of inputs and 1-to-1 transform them into something different. In this case, your _venues array is empty because you are not returning anything inside the _.map callback. The way that I have always tackled...
javascript,node.js,mongodb,mongoose
Your GET request should have worked because a browser executes a GET request by default. Try the following. app.get("/database", function(req, res) { Entry.find(function(err, data) { if(err) { console.log(err); } else { console.log(data); } }); }); As far as testing your POST route is concerned, install a plugin for Google Chrome...
mongodb,mongoose,aggregation-framework
You can convert unix epoch ms counts to native Date objects for aggregation by adding the count to new Date(0). For example: db.test.aggregate([ {$group: { _id: {$month: {$add: [new Date(0), '$created']}}, qty: {$sum: '$qty'} }} ]) Or if you want aggregate by month and year, add a $project that does...
Try to .toObject() the form: Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){ if (err) return res.send(500, { error: err }); var objForm = form.toObject(); objForm.status = "saved successfully"; return res.send(objForm); }); ...
node.js,mongodb,express,mongoose
I copied your code exactly and then was able to run it without any issues. So this most likely means there's some issue in your local environment. Most likely an old/outdated package. In your root directory, create a file called package.json with the following contents: { "name": "stackoverflow-30492214", "version": "0.0.1",...
node.js,mongodb,mongoose,nosql
I think the best choice is to use aggregation. You can $group by uniqueVal http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group And use $first for the other values http://docs.mongodb.org/manual/reference/operator/aggregation/first/#grp._S_first...
node.js,mongodb,mongoose,underscore.js,lodash
The problem is that if you don't have properties defined in your schema, and if they don't already exist, you can't create them with doc.prop = value even if you have {strict:false} in your schema. The only way to set new properties is to do doc.set('prop', value) (You still have...
javascript,node.js,mongodb,mongoose
Your index is on the wrong namespace. What you have: { "business_detail.business_location" : "2d" }, What it should be: { "business_details.business_location" : "2d" }, So the correct field here is "business_details", correct with: db.users.ensureIndex({ "business_details.business_location": "2d }) Or otherwise define that index in your mongoose schema. But also remove any...
node.js,mongodb,asynchronous,mongoose
You have to call the callback function passed to each of your waterfall functions, otherwise it won't know when it's finished. Try this: async.parallel([ function(callback) { //This is the first task, and callback is its callback task Event.find({}, function(err, events) { if (err) return callback(err); logAllThings(err,events); callback(); }); }, function(callback)...
angularjs,node.js,mongodb,mongoose
Mongodb itself is not relational database and any kind of "join" operation is not possible. I see two ways to go: Easy way, but not the best way: If you, say, need to show 30 items on a page you need: Load 30 items from Ringtone, load 30 items from...
mongodb,mongoose,mongodb-query
All of the $set, $addToSet, and $push operators will create the array if the field doesn't exist yet. Make sure you've added email to your Mongoose model's schema for the update to properly occur. var userSchema = new Schema({ name: String, emails: [String] }); All three of the below options...
`createdAt : {type: Date, default : new Date()}` Type Date not string man...
If you set pictures to an empty array you shouldn't have a value at index 0. var albumData = { album : 'album1', pictures : [] };...
Since it was the question that you actually asked that was neither really provided in the current acceptance answer, and also that it does some unnecessary things, there is another approach: var userId = 5; // A variable to work into the submitted pipeline db.sample.aggregate([ { "$unwind": "$options" }, {...
If result is a JSON string, calling .round would return undefined. Try converting the JSON to a javascript object first: result = JSON.parse(result); models.Round.findById(result.round, function(err, roundref){ console.log(roundref); ...
javascript,node.js,asynchronous,express,mongoose
You need to you asynchronous call. In your case you should use the callback: .use(function(req, res, next) { sessionHelper.isLoggedIn(function(user) { if (!user) { console.log("no"); res.locals.is_logged_in = false; } else { console.log("yes"); res.locals.is_logged_in = true; res.locals.current_user = '/users/' + req.user._id; } next(); // next MUST be here in order to continue...
node.js,mongodb,mongoose,promise
After going over it, it looks like .catch isn't actually part of the Promises/A+ specification. Most libraries just seem to implement it as syntactic sugar. The MPromise library is the promise library for Mongoose and it looks like it adheres to the bare minimum requirements of the specification. You could...
node.js,mongodb,mongoose,geospatial,geojson
The 2dshpere index should be created on the loc property, not the coordinates property. Try changing your index statement to: AreaSchema.index({loc: '2dsphere'}); Also, indexes are created in the background, sometimes taking a while to be generated, depending on the amount of existing data in the collection. Since your insert and...
javascript,node.js,mongodb,csv,mongoose
You can use async's eachSeries method. I assume that output is an array of users. Async's eachSeries will iterate over an array, process an item and, once the callback method is called, go to the next item in array : fs.readFile(file, function(err, data) { if (err) throw err; parse(data, function(err,...
express,mongoose,mocha,chai,supertest
Here's what I suggest. Let's perform the #remove on the doc found by #findOne. If I remember correctly, remove post hooks only works on Doc#remove and not on Model#remove. schema.post('remove', function (doc) { console.log('doctors - post - remove'); // <-- now runs }); app.delete('/doctors/remove', authController.isAuthenticated, function (req, res, next) {...
You could try using the $or operator on an array that contains query conditions derived from the other input array. For example, with the sample properties collection: db.properties.insert([ { "address" : { "street" : "5 Orange Drive", "city" : "Orlando", "state" : { "abbreviation" : "FL", "name" : "Florida" },...
Mongoose has a feature called population that you can use to set up "relationships" (MongoDB only has limited support for relationships). Your schema would look something like this: var UserSchema = new Schema({ name : String, group: { type: Schema.Types.ObjectId, ref: 'Group' } }); var GroupSchema = new Schema({ name...
First, you have to deal with the current state of your MongoDB collection and delete all the duplicated documents. One thing is sure : you won't be able to create the unique index with duplicates in your collection and dropDupes is now deprecated since the version 2.7.5 so you can't...
If you want parse the mongodb result, use moment.js to convert String to date : http://momentjs.com/. var date = moment("24th June 2015", "Do MMM YYYY"); // you've got a moment Date If you want convert this MongoDb String to date for queries, convert a date with monent.js to this String...
Yes, there is a performance hit. MongoDB has collection-level update locks. By keeping everything in a single collection you are ultimately limiting the number of concurrent update operations your application can perform, hence leading to decreased performance. The caveat to this, is that it totally dependant on how your application...
node.js,mongodb,mongoose,mongoose-populate
The deep-populate plugin will work for this, but you need to use the right path to the deepest field you want populated. In this case, the query should look like this: Parent.findOne().deepPopulate('childs.subject.data').exec(function(err, parents) {...}); However, it's important to realize this uses multiple queries (at least one per population level) to...
The way event emitter works is that you have to use the same event emitter object to listen on that you used to emit. So you need something like this: To share this among different parts of your project you should create a module out of it and require it...
First of all the schema you posted is off, should be { album : "album1", pictures: [ 1.jpg, 2.jpg, 3.jpg ] } note "pictures" is an array not an object. You can add to the array with //SAVE DB AlbumPhoto.update({album:'album1'}, {$push: {pictures: "new.jpg"}}, function(err, data){ if(err){ console.log(err); } }) ...