Menu
  • HOME
  • TAGS

Mongoose: Bulk insert via Model.collection.insert crashes Node.js with Segmentation fault 11

node.js,mongodb,mongoose

Found the answer. The problem is that I push mongoose Model instances into the array. But only plain objects are allowed.

How to add extra parameters to a function callback

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){}; ...

Mongoose method undefined

node.js,mongodb,mongoose

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() {...

$unset is empty. You must specify a field like so: {$unset: {: …}}

node.js,mongodb,mongoose

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} ) ...

Remove object attribute with array map

javascript,arrays,mongoose

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();...

node.js saving form data using mongoose/mongodb/express has errors and wont work?

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....

How to add a subdocument in a mongoose schema

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];...

Receiving “TypeError: Object # has no methods 'updateMyField'” in a post-save hook

mongoose

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?.

How to save object immediately in MongoDB?

node.js,mongoose

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...

How can I push element to array in http.put in angularjs?

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);...

How to get data back from Mongoose without using a callback?

node.js,mongodb,mongoose

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...

Getting a list/array of users using Mongoose populate

node.js,mongodb,mongoose

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...

Mongoose populate not returning results

node.js,mongodb,mongoose

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 }; ...

Mongoose find and findOne middleware not working

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...

Add elements to an array in MongoDB using Mongoose

node.js,mongodb,mongoose

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...

Select Mongoose Model Based on Express Route

express,routing,mongoose

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...

Angular nested repeat, save to database not working

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"...

Mongoose embedded document update not persisting

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);...

NodeJs + ExpressJs app routing odd behavior

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.

Mongoose - Get list of _ids instead of array of objects with _id

node.js,mongodb,mongoose

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 Express ejs Error: Failed to lookup view “error” in views directory

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) { /*...

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

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....

Mongoose installation failed on Mac

node.js,mongodb,mongoose

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...

How to catch the error when inserting a MongoDB document which violates an unique index?

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...

Node.js, MongDB (Mongoose) - Adding to data retrieved.

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...

how give different privilege for user and admin in mongodb

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...

mongoose get property from nested schema after `group`

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,...

Create a text index on MongoDB schema which references another schema

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...

I'd like to count the documents with the matching “name” property AND group them by “name” at the same time

node.js,mongoose,group-by

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...

Value property change not being reflected when logging value of Mongoose-created object

javascript,node.js,mongoose

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...

mongoose validation matching an array with another array for common string?

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'); --...

Mongoose update 'cannot use the part (..) to traverse the element

node.js,mongodb,mongoose

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

Node mongoose always returning error on findOne

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) { ...

show records based on user role

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')) {...

MEAN Stack Error when calling two diferent api's routes at the same time

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...

Mongoose model doesn't work well

json,node.js,mongodb,mongoose

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 =...

Mongoose: Linked Model Schema “Hasn't Been Registered for Model”

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...

Mongoose - Searching Schema via findOne() unsuccessfully

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...

Mongodb database schema design issue

mongodb,mongoose

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...

Trouble with $gt in mongoose

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...

Find by id or username in mongo

node.js,mongodb,mongoose

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...

Getting a CastError NaN for a Number

javascript,mongodb,mongoose

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...

How to aggregate common values in Mongo?

mongodb,mongoose

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": {...

Saving subdoc ref and parent document simultaneously

mongodb,mongoose,mean-stack

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.

Mongoose schema: 'unique' not being respected

mongodb,mongoose

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') ...

Why does mongoose model's hasOwnProperty return false when property does exist?

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...

Mongoose population in instance methods

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....

Mongoose Validation Error occurs on OpenShift but not local version

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({...

Missing field in Mongo/Mongoose Query Results

node.js,mongodb,mongoose

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....

Angular is not sending objects in objects

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....

Save hierarchical nodes from json file into mongodb using mongoose on a node server

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() } }); }); ...

Set default date in Mongoose document to now + [some increment]

mongodb,mongoose

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...

Mongoose findByID return no error when id not set [duplicate]

node.js,mongodb,mongoose

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...

How to remove a document in Mongoose, only if one of its fields matches some condition?

node.js,mongodb,mongoose

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(); ...

Object # has no method 'catch'

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 ...

Need to send response after forEach is done

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...

Using Mongoose.js Model.Remove(conditions, callback) - remove successful but callback not being called

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...

Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema

You can try this: objectModel.find({ 'members.user_id' : {'$in' : ['asdf123lkd', 'asdf1223']} }, function(err, data) { console.log(err,data); }) ...

What will happen if unwind is applied to a field which is not present while using aggregation in mongoose

node.js,mongodb,mongoose

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...

Displaying only the title on the client returns undefined

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 });...

Nodejs callback hell in foreach

json,node.js,express,mongoose

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...

How to update and read a collection in MongoDB using Mongoose

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...

Aggregate data stored as time_t in MongoDB

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...

unable to add property to the json object

node.js,express,mongoose

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); }); ...

“Simple” RESTful API using node/mongo/express

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",...

How to find documents with unique values in MongoDB?

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...

setting up fake data in mongodb for testing

database,node.js,mongodb,testing,mongoose

You could try to write json files instead of code and use mongoimport to recreate your database. That's easier to maintain than kilometers of very verbose and repetitive code.

Why can't I seem to merge a normal Object into a Mongo Document?

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...

Error when trying to query with $near in find()

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 Async only doing one callback

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)...

How to combine two collections in Mongoose and sort them using createdDate

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...

How to add a new array field to collection in mongodb?

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...

Mongoose Sorting

node.js,mongodb,mongoose

`createdAt : {type: Date, default : new Date()}` Type Date not string man...

How update the first element of an array in mongoDB?

node.js,mongodb,mongoose

If you set pictures to an empty array you shouldn't have a value at index 0. var albumData = { album : 'album1', pictures : [] };...

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

database,node.js,mongodb,mongoose,mongolab

Try using db = mongoose.connect(uri); instead of db = mongoose.createConnection(uri); ...

How to do mongoose aggregation with nested array documents

node.js,mongodb,mongoose

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" }, {...

mongoose findById works when I use a string literal but not when I reference a property of an Object

node.js,mongodb,mongoose

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); ...

Node: how to implement isLoggedIn before all routes?

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...

Why can I not chain .catch when calling mongoose Model.create in node

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...

Failure when searching for all polygons near a point using mongoose/mongodb

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...

Creating unique Mongoose objects from CSV

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,...

Supertest and Mongoose Middleware (post remove)

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) {...

Mongo/Mongoose - Find by partial document

node.js,mongodb,mongoose

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" },...

How would I develop a relationship User belongs to Groups in Mongoose & Node.js?

node.js,mongodb,mongoose

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...

Unique key in moongose db

mongodb,mongoose

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...

How can I convert a date string from Mongoose Query?

javascript,date,mongoose

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...

mongodb performance when updating/inserting subdocuments

node.js,mongodb,mongoose

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...

Mongoose, Deep Population on array model

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...

How to emit event in mongoose middleware?

node.js,events,mongoose,emit

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...

Mongoose : update collection with previous data

node.js,mongodb,mongoose

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); } }) ...