FAQ Database Discussion Community


Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema
This is my collection schema: var objectSchema = new Schema({ members: [{ user_id: ObjectId, settings: { type: Boolean } }], title: String }); And now I'm trying to search for objects with specific members (identified by their "user_id", for example ["asdf123lkd", "asdf1223"]). Is there any way to search for these...

How to find documents with unique values in MongoDB?

node.js,mongodb,mongoose,nosql
I have a collection with several documents in it of jobs to process using another system. I look up 5 objects from this table like this: Work.find({status: 'new'}) .sort({priority: 'desc'}) .limit(5) .exec(function (err, work){}) There is another field on these documents which determines that only one job with a given...

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

node.js,mongodb,mongoose
I have 10,000,000 documents that I want to insert into a MongoDB. I use mongoose to create the documents of the parsed JSON (the JSON is created by transforming the content of a lot of txt files). I started using Model.create for each document, but it was way to slow...

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

node.js,mongodb,mongoose,geospatial,geojson
I am trying to search for any GeoJSON polygon that is with x number of kilometers from a point ordered by distance from the point. It's important that it is a GeoJSON polygon and not a GeoJSON point. I have the following but I get an error: 'Unable to execute...

Create a text index on MongoDB schema which references another schema

javascript,node.js,mongodb,indexing,mongoose
I am trying to add an index to a certain Schema with mongoose for text searches. If I add a text index to individual fields it works fine, also with compound indexes it is okay. For example the answer provided here is great: Full text search with weight in mongoose...

How to aggregate common values in Mongo?

mongodb,mongoose
I have following document : { asset : { assetName : abc, attributes : { Artist : XYZ, Duration : 10 } } } { asset : { assetName : pqr, attributes : { Artist : EFG, Duration : 5 } } } { asset : { assetName : HIJ,...

Mongo DB relations between documents in different collections

node.js,mongodb,express,mongoose
I'm not yet ready to let this go, which is why I re-thought the problem and edited the Q (original below). I am using mongoDB for a weekend project and it requires some relations in the DB, which is what the misery is all about: I have three collections: Users...

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

database,node.js,mongodb,mongoose,mongolab
I've been trying to use mongoose (module for node.js and mongodb). And tried to get a connection with mongolab up and running. I tried the following at the top of my app.js file, but I couldn't seem to enter the db.on function. global.mongoose = require('mongoose'); var uri = 'mongodb://username:password#####@ds.mongolab.com:#####/db'; global.db...

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

javascript,node.js,mongodb,mongoose
I currently have the following code: User.find({ featuredMerchant: true }) .lean() .limit(2) .exec(function(err, users) { if (err) { console.log(err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { _.forEach(users, function(user){ _.forEach(user.userListings, function(listing){ Listing.find({ user: user }).populate('listings', 'displayName merchantName userImageName hasUploadedImage').exec(function(err, listings){ user.listings = listings; }); }); }); res.jsonp(users); } }); As...

Mongoose Populate with express res.json() breaks

json,node.js,mongodb,express,mongoose
So I'm selecting Activities from the mongodb and populating User for each. var query = Activity.find(query).populate("user"); return query.sort({created:"desc"}).exec(function(err, activities) { debugger; if (!err) { return res.json(activities); } else { res.status(400).json(err); } }); As you can see I have a debugger; breakpoint is there, When I'm pring activities it prints an...

Object # has no method 'catch'

node.js,mongoose,promise,bluebird
My user lib have following code for register function register { // do some validation on lib level //user is instance of user collection user.save() .then(function(error,records, numberOfRecords) { // got any kind of error if (error) { next('fail',msg,{error_code : 510, exception : ex} ) return ; } next('success','good', records );...

Nodejs callback hell in foreach

json,node.js,express,mongoose
i have a venues data. i want to get how people in here now after that compress venues data and count data to json. This code is working but json result is null. var _venues = _.map(venues.response.venues, function (v) { Checkin.where({ 'venuesUniqeId': v.Id, 'createdDate': { $gte: new Date().getHours() - 2...

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

node.js,mongodb,mongoose,passport.js
I have this code : user.findOne( { 'email' : email }, function( err, User ) { if ( err ) { return done(err); } if ( !User ) { return done(null, false, { error : "User not found"}); } if ( !User.hasOwnProperty('local') || !User.local.hasOwnProperty('password') ) { console.log("here: " + User.hasOwnProperty('local'));...

Supertest and Mongoose Middleware (post remove)

express,mongoose,mocha,chai,supertest
I have been fiddling with this for days, and I cannot figure out why the Mongoose middleware is not being invoked. So I have an API in node.js and I have a website using Angular.js. The Mongoose middleware is this: schema.post('remove', function (doc) { console.log('doctors - post - remove'); });...

Mongoose installation failed on Mac

node.js,mongodb,mongoose
This was what I got in my terminal. I have mongoDB and node.js installed already.. If anyone can help me with this I'll appreciate it a lot! Thank you... ...

unable to add property to the json object

node.js,express,mongoose
I am trying to add status to a response on successful update but I am not able to add the status property to json object of form. Here is my code apiRouter.post('/forms/update', function(req, res){ if(req.body.id !== 'undefined' && req.body.id){ var condition = {'_id':req.body.id}; Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){ if (err)...

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

javascript,json,node.js,mongodb,mongoose
I have a JSON file with a list of categories: "data": { "categories": [ { "id": 1, "name": "Clothes", "children": [ "Womens", "Mens", "Children", "Baby", ] }, { "id": "13", "name": "Womens", "children": [ "Womens Tops", "Womens Bottoms", "Womens Accessories", ] }, { "id": "33", "name": "Womens Tops", "children": []...

Angular nested repeat, save to database not working

angularjs,node.js,mongoose,mean-stack
I'm using a MEAN application, and now I want to read data from my database, allow users to edit it, and update the changes to the database. Everything is working fine, except for the nested repeat, which value's I'm able to get, but not save to the database. Code: <div...

Mongoose aggregation of documents with similar values in array

node.js,mongodb,mongoose
I am trying to find the solution to a problem but don't get any further. I have a number of documents in my collection, each containing an array with some values: [{id:0,arr:[1,2,3,4]},{id:1,arr:[4,5,6,7]},{id:2,arr:[3,7,8]}] I am trying to build an aggregation pipeline which would allow me to order the documents sorted by...

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
Let's say I have a User collection: schema = mongoose.Schema({ firstName: { type: String, required: true }, ... ... }); module.exports = mongoose.model("User", schema); I would like to write a mongoose query that would count how many users go by the name Mike, Andy, Jerry... In other words, I would...

Node: how to implement isLoggedIn before all routes?

javascript,node.js,asynchronous,express,mongoose
I want to write a helper function isLoggedIn , which is used for judge if the any user has logged in, if logged in, set res.locals.is_logged_in = true. var isLoggedIn = function(req, res, next) { User.findById(sessions.user_id, function(err, user) { if (err) throw err; return !user ? false : true; });...

How do you get the created object of a findOneAndUpdate with {upsert: true} in MongooseJS? [duplicate]

node.js,mongodb,mongoose,mean-stack,meanjs
This question already has an answer here: Mongoose findByIdAndUpdate upsert returns null document on initial insert 1 answer What I am doing: Book.findOneAndUpdate( {_id: id_from_api}, {$set: bookObj}, {upsert: true}, function (err, book) { handleError(err); console.log(book); } ); I am expecting book to be a book document but it is...

Should I use mixed or individual data in a mongoose schema?

mongodb,mongoose
If I have a schema for an order, what would be a better design, this: var schema = new Schema({ name: String, timePlaced: Date, packageDimensions: {height: Number, width: Number, weight: Number } }) Or this var schema = new Schema({ name: String, timePlaced: Date, height: Number, width: Number, weight: Number...

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

arrays,node.js,mongodb,mongoose,schema
My schema looks like this: var ArticleSchema = new Schema({ ... category: [{ type: String, default: ['general'] }], ... }); I want to parse through all records and find all unique values for this field across all records. This will be sent to the front-end via being called by service...

Select Mongoose Model Based on Express Route

express,routing,mongoose
I think this might be a basic question, but looking for the best approach. I'm building an express app that should route to one of four different Mongoose models depending on the route. Something like this: app.get('/:trial', function(req, res){ var trial = req.params.trial; trial.find(function(err, records) { if (err) res.send(err); res.json(records);...

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

node.js,mongodb,mongoose
I would like to run following query: Group.find({program: {$in: [...]}}).lean().select('_id') And then NOT get following back: [{_id: ...}, {_id: ...}, {_id: ...}, {_id: ...}] BUT following: [..., ..., ..., ...] where ... represents an _id of a Group Of course I could just run the query and then loop through...

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

javascript,node.js,mongoose
I am iterating through items in an object using the forEach method. function scrapeRssFeedData(rssFeeds, cb){ rssFeeds.forEach(function(rssFeed){ rssFeed.property = 'value'; console.log(rssFeed.property); console.log(rssFeed); }); } The value that is logged for rssFeed.property is, correctly 'value'. However, when the rssFeed object itself is logged, the property is not visible. The original rssFeeds object...

Remove object attribute with array map

javascript,arrays,mongoose
I have an array of objects. Each element of the array has an attribute that I would like to remove. My code: //remove the version key '__v' var elements = elements.map(function (element) { if (element.__v !== undefined) { delete element.__v; //console.log(element.__v); } return element; });//elements.map() console.log(elements); If I uncomment the...

How to use MongoDB findOne() with mongoose

node.js,mongodb,mongoose,mean-stack
I'm having troubles using the MongoDB findOne() function together with mongoose. controller exports.show = function (req, res) { Fahrt.load(req.params.fahrtenId, function (err, fahrt) { res.jsonp(fahrt); }); }; model FahrtSchema.statics = { load: function (id, cb) { this.findOne({ _id: id } ).exec(cb); }}; route router.get('/:fahrtId', fahrtenController.show); app.js app.use('/fahrten', fahrten); When I use...

Transform results of an array returned by Mongoose find function

node.js,mongodb,mongoose
I have added a transform function to my Schema's toObject to strip certain properties, and change the name of _id to id. It works great when I use findOne and call toObject on the result, but I also have a find({}, (err, items) => {...}) command. There's no way to...

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

mongodb,mongoose
Looking at setting a default timestamp for a document to now + 1 minute/hour/day. How would I go about modifying this to do so: date: { type: Date, default: Date.now } ...

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

javascript,mongodb,express,mongoose,mean
I'm building a MEAN app. This is my Username schema, the username should be unique. var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('User', new Schema({ username: { type: String, unique: true } })); On my post route I save the user like this: app.post('/authenticate', function(req, res) {...

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

javascript,node.js,mongodb,mongoose
i'm trying to use the $near operator with $find(), however i can't managed to get it done. i have tried 2 methods userSchema var userSchema = new db.Schema({ email: { type: String, unique: true, lowercase: true }, password: { type: String, select: false }, company_name: String, location_verified: { type:Boolean, default:false},...

Query Mongoose Documents Based on Object Properties

arrays,node.js,mongodb,mongoose
I have the following Mongoose Schema: var UserSchema = new Schema({ name: String, age: Number, ... tags: [{ text: String, ... }] }); and the following array: var tagTexts = ['tall', 'small', 'green', 'blue']; I would like to retrieve all user documents that contain at least one tag with a...

Find by id or username in mongo

node.js,mongodb,mongoose
I'm trying to do a find by username or _id like this exports.getUser = function (req, res){ User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] }) .exec(function (err, collections) { res.send(collections); }); }; It works when I search by _id but fails for username because it fails to return a valid OjectID....

Mongoose schema: 'unique' not being respected

mongodb,mongoose
I'm trying to use Mongoose with this schema var RestoSchema = new Schema({ "qname" : {type: String, required: true, unique: true}, ... }); The problem is that this still permits new entries to the database to be created with an existing qname. From what i can see below the index...

mongoose setting referenceone

javascript,node.js,mongodb,asynchronous,mongoose
Hello can someone help me. I can't set mongoose model field Here my institute.js model file var mongoose = require('mongoose'); var Schema = mongoose.Schema; var instituteSchema = new Schema({ name: {type: String, required: true}, idApi: {type: String, required: true}, country: { type: Schema.ObjectId, ref: 'Country' }, created_at: {type: Date, default:...

Mongoose - Searching Schema via findOne() unsuccessfully

node.js,mongodb,mongoose,express-session,connect-mongo
In setting up a sessionStore via MongoDB for express-session, I'm having a little trouble using the findOne() function to verify that a user's information is valid and recent. var session = require('express-session'); var mongoStore = require('connect-mongo')(session); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Session = mongoose.model('session', new Schema({...

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

node.js,mongodb,mongoose
This question already has an answer here: node.js mongojs findOne callback returning error as null 1 answer I have a collection with an ID (_ID). { "_id": ObjectId("5583df9da55f654609901eed"), "group": "Tomorrowland", "description": "Délire 2015 à Tomorrowland", "uid": [ "5583df21a55f654609901eec", "5583e8ef9aeb31390bb50bf6" ], "pictures": [ "1434705960113.jpg", "1434705974710.jpg", "1434706147177.jpg", "1434711007201.jpg" ], "__v": 0...

How update the first element of an array in mongoDB?

node.js,mongodb,mongoose
I am learning NodeJs and MongoDb and I will create a photo album. I encounter a problem with mongoDB. In fact, after uploading a picture, I push new pictures into the database like this : AlbumPicture.update({album:'album1'}, {$push: {pictures:file_name}}, function(err, data){ if(err){ console.log(err); } console.log('Database Updated'); }); The problem is :...

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

angularjs,mongodb,api,mongoose
I have the following schema: var UserSchema = new Schema({ name: String, email: { type: String, lowercase: true }, projects: [{type: Schema.ObjectId, ref:'Project'}], //.... } How can I add projectId by using http.put? This is among the things that I have tried: $http.put('/api/users/'+User._id, {'projects': project._id}); ...

How to emit event in mongoose middleware?

node.js,events,mongoose,emit
I want to emit event when new blog saved blog.post('save',function(blog){ this.emit('newBlog',blog) }) and somewhere else in my project say app.js can listen this event EventEmitter = require('events').EventEmitter; emitter = new EventEmitter(); emitter.on('newBlog',function(blog){ console.log(blog); }) how to do this?...

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

javascript,node.js,mongodb,express,mongoose
Currently using Mongoose with MongoDB for an Express server, however I attempted to link up several Mongoose models together and I am getting MissingSchemaError: Schema hasn't been registered for model "Semester". Use mongoose.model(name, schema) with my execution. The current project structure is as follows app.js www.js models |-- member.js |--...

Angular is not sending objects in objects

angularjs,node.js,mongodb,express,mongoose
I'm sending this JSON with Angular.js to my node.js/express.js service: { "name": "MyGuitar", "type": "electric", "userid": "123", "likes": 0, "dislike": 0, "guitarParts": { "body": { "material": "/content/img/hout.jpg", "_id": "5566d6af274e63cf4f790858", "color": "#921d1d" }, "head": { }, "neck": { "material": "/content/img/hout.jpg", "_id": "556d9beed90b983527c684be", "color": "#46921d" }, "frets": { }, "pickup": { },...

Mongoose, Deep Population on array model

node.js,mongodb,mongoose,mongoose-populate
I would like to deep populate a perhaps overcomplicated model var ParentSchema = new Schema({ childs: [{type:Schema.ObjectId, ref: 'Child'}], }); var ChildSchema = new Schema({ subject: [{ price: {type: Number}, data: {type: Schema.ObjectId, ref: 'Subject'} }] }) However, it doesn't seem to work when i use the regular population. I...

Mongoose Validation Error occurs on OpenShift but not local version

node.js,mongodb,mongoose,openshift
I am migrating my Node.js server with Mongoose to OpenShift and an error occurs on the live server that I cannot reproduce on my local WebStorm built-in server. I get the error message: undefined: { properties: { message: "Cannot read property 'options' of undefined" type: "cast" }- message: "Cannot read...

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

mongodb,mongoose,mongodb-query
For example, I have a collection, such as User, with one field name (and default _id field). I insert some documents to this collection. Then I want to add a field emails (which is an array to insert multiple emails) to this collection. If it is a normal field (not...

Node mongoose always returning error on findOne

javascript,node.js,mongodb,mongoose,passport.js
I'm using passport.js to sign in users, and whenever my local authentication function gets to User.findOne(), it always returns with an error. I have no idea what I'm doing wrong... my passport code with the findOne() call: passport.serializeUser(function(user, done) { console.log('serialize user occurred'); done(null, user.id); }); // used to deserialize...

Missing field in Mongo/Mongoose Query Results

node.js,mongodb,mongoose
I am trying to publish a node app to my Raspberrypi (the closest thing I have to a dedicated server XD ) for some of my friends to test a little web-app I wrote, but for some reason one of the queries is not working correctly on the pi when...

Node.js Async only doing one callback

node.js,mongodb,asynchronous,mongoose
I'm just doing my first bit of Node async stuff, I wanted to do two queries to a DB and then print the results one after the other, my code is as follows: console.log(req.query); function logAllThings(err,things){ if (err){ console.log(err); } else { console.log(things); }; }; async.parallel([ function(callback) { //This is...

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

node.js,mongodb,mongoose
I have this really annoying issue where i can't update anything using mongoose. It's really frustrating to use, and the documentation is not helping at all. I have this schema: var userSchema = mongoose.Schema({ local : { email : String, password : String, }, devices : [{ id : String,...

Unique key in moongose db

mongodb,mongoose
I have the following DB: { "_id" : ObjectId("556da79a77f9f7465943ff93"), "guid" : "a12345", "update_day" : "12:05:10 02.06.15" } { "_id" : ObjectId("556dc4509a0a6a002f97e972"), "guid" : "bbbb", "update_day" : "15:03:10 02.06.15" "__v" : 0 } { "_id" : ObjectId("556dc470e57836242f5519eb"), "guid" : "bbbb", "update_day" : "15:03:10 02.06.15" "__v" : 0 } { "_id" :...

Mongoose population in instance methods

node.js,mongodb,mongoose,mongoose-populate
I have a model with reference to other documents. I would like to have a method in that model that can process data used in the referenced models. 'use strict'; var mongoose = require('mongoose') , Schema = mongoose.Schema , deepPopulate = require('mongoose-deep-populate'); var MainSchema = new Schema({ childs: [{type:Schema.ObjectId, ref:...

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

node.js,mongodb,mongoose,promise
I have a mongoose schema and am calling Model.create(). When I chain 'catch' after the 'then' I get undefined is not a function, if I just call the error function as the second parameter to the 'then', then I don't. But when I call methods such as Model.find, I can...

How to save object immediately in MongoDB?

node.js,mongoose
In my Node application I use the mongoose module. I found out that after model_name.create({...}) object is not created immediately but with some delay (buffer?). How can I force to save this new object in this particular moment?...

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

node.js,mongodb,callback,mongoose
I've simplified down to the following most basic possible version... UserModel.remove({ }, function (err) { console.log("inside callback"); }) I've verified that the records are being removed but the callback is never called. I've successfully added documents using var user = new UserModel(req.body); user.save(function (err) { if (err) { return (next(err));...

Mongoose embedded document update not persisting

node.js,mongodb,mongoose,mean-stack
I'm currently working with the MEAN stack and I'm trying to update an embedded document. Everything appears to work on execution, but the data does not persist after a refresh: // Soon to be update answer exports.updateAnswer = function(req, res) { var ansId = req.params.aid; var result; Poll.findById(req.params.id,function(err, poll){ if(err)...

Mongoose find and findOne middleware not working

node.js,mongoose,find,middleware
If have the following schema and middleware hooks, but the find and findOne hooks are never being called. The save and update hooks work as expected. According to the Mongoose Middleware documentation, this should be available. // define the schema for our recs model var recSchema = mongoose.Schema({ dis: String,...

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

node.js,mongodb,mongoose,underscore.js,lodash
I have a data feed from a 3rd party server that I am pulling in and converting to JSON. The data feed will never have my mongoDB's auto-generated _ids in it, but there is a unique identifier called vehicle_id. The function below is what is handling taking the data-feed generated...

Mongoose model doesn't work well

json,node.js,mongodb,mongoose
These days, i am working for a project that need to keep some information about analytic by using NodeJS and MongoDB. When i try to send JSon data, some parts are saved into database but most parts of the data are losing. I couldn't understand where i am doing mistake....

Node Express ejs Error: Failed to lookup view “error” in views directory

node.js,mongodb,express,mongoose,ejs
I am making an express app with ejs and mongoose. I am getting this error: Error: Failed to lookup view "error" in views directory "/Users/ben/Documents/csMSc/web/site/app/views" at EventEmitter.app.render (/Users/ben/Documents/csMSc/web/site/app/node_modules/express/lib/application.js:555:17) at ServerResponse.res.render (/Users/ben/Documents/csMSc/web/site/app/node_modules/express/lib/response.js:938:7) at module.exports (/Users/ben/Documents/csMSc/web/site/app/app.js:94:7) at Layer.handle_error...

Mongo/Mongoose - Find by partial document

node.js,mongodb,mongoose
I have a collection of properties that all have addresses. "address" : { "street" : "5 Orange Drive", "city" : "Orlando", "state" : { "abbreviation" : "FL", "name" : "Florida" }, "zip" : "32822", "geo" : { "lat" : 28.519, "lng" : -81.304 } }, "address" : { "street" :...

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

node.js,mongodb,mongoose
I'm having a really strange problem in Mongoose. This line correctly finds the Round: models.Round.findById("555ec731385b4d604356d8e5", function(err, roundref){ console.log(roundref); .... This line DOES NOT models.Round.findById(result.round, function(err, roundref){ console.log(roundref); I've console logged result and it clearly is an object containing the property round: {round: "555ec731385b4d604356d8e5", selection: 1, time: 20} Why won't findById...

Need to send response after forEach is done

node.js,mongodb,express,mongoose
I'm working with NodeJS + Mongoose and I'm trying to populate an array of objects and then send it to the client, but I can't do it, response is always empty because it is sent before forEach ends. router.get('/', isAuthenticated, function(req, res) { Order.find({ seller: req.session.passport.user }, function(err, orders) {...

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

angularjs,node.js,mongodb,mongoose
I am developing application using MEAN.js in which I have two documents as below: var RingtoneSchema = new Schema({ language: { label: String, code : String }, deliver:{ type:Boolean, default:false }, artists: [RingtoneArtist], digital_booklet:{ title: { type: String, trim:true }, copyright:{ type: String, trim:true } } title: { type: String,...

Mongoose populate not returning results

node.js,mongodb,mongoose
I am trying to use populate to return results that are ref to the Stamp model, under the users array of stamps but for some reason it does not return any results when I see in the database a list of stamp ids in the stamps array... Here is my...

How to add a subdocument in a mongoose schema

javascript,node.js,mongodb,mongoose
I am trying to create a subdocument in a mongoose schema from node.js/Express. I have two schemas: Member and Address Member.js // app/models/member.js // load mongoose since we need it to define a model var mongoose = require('mongoose'), Schema = mongoose.Schema var Address = require('./address'); var MemberSchema = Schema({ FName...

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

angularjs,node.js,mongodb,mongoose,mongolab
Having some issues with angularjs, mongoose or MongoLab. If a make two api calls to different api route at the same time, the data won't load. So i got it working by waiting for each call to finish (with promise) before making the next call. This way for me doesn't...

Mongoose Sorting

node.js,mongodb,mongoose
I have a problem with displaying data with sorting. Here is my query, Activity.find({"user_id": sesUser._id}, {}, {offset: 0, limit : 5, sort:{createdAt:1}}, function (e,a){ ... }); I have data about 252 length, and my latest data is 9 June 2015. If i use this query i only get data from...

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

javascript,node.js,mongodb,express,mongoose
I am using express and mongoose to save my form data to my mongodb database but the operation won't work as it gives me an error that my model is not registered. my code: index.ejs <!DOCTYPE html> <html> <head> <title>Admin-Page</title> </head> <body> <h1>admin-dashboard-interest</h1> <form method="post" action=""> <label for="select1">min select:</label> <select...

setting up fake data in mongodb for testing

database,node.js,mongodb,testing,mongoose
We have a project in which we need to create a fake database and fake data for functional testing. Initially we started with a script that creates the entities using mongoose, initializes them and save them. var StudentA = new Student(); StudentA.name = "Bob"; StudentA.surname = "Marley"; StudentA.save(); As the...

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

javascript,arrays,node.js,mongodb,mongoose
My mongoose Schema + validation var schemaInterest = new schema({ active_elements: { type: [String] }, pending_elements: { type:[String] } }); schemaInterest.methods.matchElements = function matchElements() { this.find({active_elements: this.pending_elements}, function(){ //shows all the matched elements }); }; I don't know how to work with error handling in mongoose yet. I want it...

“Simple” RESTful API using node/mongo/express

node.js,mongodb,express,mongoose
I am completely new to server side javascript so any help would really be appreciated. I recently followed this tutorial https://www.youtube.com/watch?v=p-x6WdwaJco to build a simple RESTful API with node.js mongodb and express. The tutorial also uses a library called node-restful https://github.com/baugarten/node-restful. First of all I built a server.js in the...

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

node.js,mongodb,mongoose
Ultimately my knowledge is so bad as I started just a few hours ago. But in my head this should work: getAll: function(callback){ User.find({}, function (err, data) { if (err) return console.error(err); return data; }); } var users = api.getAll(); console.log(users); //undefined But for some reason I have to pass...

how give different privilege for user and admin in mongodb

javascript,mongodb,mongoose,sails.js
I'm creating the an application using sails and MongoDB. where I need three level of user. Super admin admin user 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...

How to update and read a collection in MongoDB using Mongoose

javascript,node.js,mongodb,mongoose
I am having trouble with a project I am working on. I want to create a database in which I can store dates and links to YouTube videos in a MongoDB database. I am using Mongoose as the ORM. The problem seems to be that the database and collection is...

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

node.js,mongodb,mongoose
I want to delete one item only if it matches some condition. It would be something like this: Session.findOne({ id:req.body.sessionId },function(err,session){ if(session.user == req.body.userId) { session.remove(); } }); Which obviously doesn't work. How can I achieve that?...

mongodb performance when updating/inserting subdocuments

node.js,mongodb,mongoose
I have a mongo database used to represent spreadsheets with three collections representing respectively cell values (row, col, value), cell formatting (row, col, object representing the format) and cell sizes (whether it's a row or column size, its index and the size). Every document in all the collections also has...

show records based on user role

angularjs,node.js,express,mongoose
I have a app which has roles e.g "user,admin". In the controller I check if the user is admin "req.user.roles.indexOf('admin') > -1" to display all records otherwise display only users records. I was wondering if there is a better way of doing this or is this the way to go....

Trouble with $gt in mongoose

angularjs,node.js,mongodb,mongoose
I've successfully queried what I'm trying to in the mongo CLI, with the following query. db.catches.find({'weightTotal': {'$gte' : 150} }) However, when I try to send a query up from angular to the route as such (with a little more specificity): Hatchery.getByLocation( { 'x': $scope.y.x._id, 'city': place.data[0].city, 'weightTotal': {'$gte' :...

Getting a CastError NaN for a Number

javascript,mongodb,mongoose
I get this error { [CastError: Cast to Number failed for value "NaN" at path "area"] message: 'Cast to Number failed for value "NaN" at path "area"', name: 'CastError', kind: 'Number', value: NaN, path: 'area' } } } for this code MySchema.methods = { updateArea: function (oldArea, newArea) { var...

Getting a list/array of users using Mongoose populate

node.js,mongodb,mongoose
I'm trying to do is display a list of user display names on one of my webpages by doing a simple http get request. In my users.server.controller.js file I have this function: exports.list = function(req, res) { User.find().populate('displayName').exec(function(err, users) { console.log(users); if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); }...

mongoose get property from nested schema after `group`

node.js,mongodb,express,mongoose
Having this mongoose schema structure: OrderSchema = new Schema({ name: String, subtotal: Number, tax: Number, date: { type: Date, default: Date.now }, location: { type: ObjectId, ref: 'Location' } }); ... LocationSchema = new Schema({ name: String }); ... I'm trying to get a group aggreation by location, but I...

Mongodb database schema design issue

mongodb,mongoose
I have two collections in my mongodb database :- Users , Clubs User Schema :- var UserSchema = new Schema({ Name: { type: String , required: true }, Clubs: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Club'} ]}); Now when a user joins a club , i update the club array . But...

How to do mongoose aggregation with nested array documents

node.js,mongodb,mongoose
I have a Mongodb collection, Polls with following schema { "options" : [ { "_id" : Object Id, "option" : String, "votes" : [ Object Id ] // object ids of users who voted },..... ] } Assume i have userId of the user in node js to whom I...

Mongoose : update collection with previous data

node.js,mongodb,mongoose
I am learning NodeJs and for a demo project i need to use MonGoDB with Mongoose. I created a collection for a photo album. The first row is : albumName and the second row is : pictures. I don't undersand how i can save all my pictures in the row...

NodeJs + ExpressJs app routing odd behavior

angularjs,node.js,express,mongoose,passport.js
I am learning ExpressJS. So far I have setup a simple todo app with user authentication using PassportJS. I use Mongoose for repository. There is nothing in the web to explain the odd behavior that I'm seeing with my route setup. Scenario: When I hit get /passport it will direct...

Add elements to an array in MongoDB using Mongoose

node.js,mongodb,mongoose
First of all, let me start by providing my MongoDB schema. showTitle: String, seasons: [{ seasonNumber: String, episodes: [{ episodeNumber: String, episodeTitle: String, episodeSynopsis: String }] }] The basic idea for this collection is to store tv show details. The TV shows can contain multiple seasons and each seasons contain...

Mongoose method undefined

node.js,mongodb,mongoose
I'm trying to create a 'checkPassword' method for my User model, however whenever I call it I get the following error: User.checkPassword(password, hash, function(err, samePassword){ ^ TypeError: undefined is not a function I'm pretty new to mongoose so I'm not sure where I'm going wrong. users.js (User model) var mongoose...

Creating unique Mongoose objects from CSV

javascript,node.js,mongodb,csv,mongoose
Let's say that I have a CSV containing information that needs to be parsed into different Mongoose objects. I need to either find or create a "User" based on a some information in the CSV file. If I run this, however, it will create a new User each time, since...

How can I convert a date string from Mongoose Query?

javascript,date,mongoose
My Mongoose date query return the below string: 24th Jun 2015 How to convert it to javascript date object?...

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

node.js,mongodb,mongoose
I am trying to teach myself node.js, coming from Rails, and I want to establish this relationship: A group has_many users, a user belongs_to group How would I go about doing this in my models? //for user var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({...

Saving subdoc ref and parent document simultaneously

mongodb,mongoose,mean-stack
I have a users model with a ref to company. My data is as follows: { "name":"justin", "notes":"hello notes", "company": {"name":"acme inc"} } Is it possible to save my data as a single call or would I need to save my company model first, then save my user afterward? var...

Aggregate data stored as time_t in MongoDB

mongodb,mongoose,aggregation-framework
I have a collection of documents stored in MongoDB which include a created field as a unix style time_t: e.g. {"created": 1137459055216, "qty": 3 } How can I aggregate this data by month through a query?...

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

node.js,mongodb,mongoose
mongodb version 3.0.1 mongoose version 4.0.3 I'm trying to do this: groupsModel.updateQ({_id:group._id},{ $unset:{"moderators":""}, $set:{"admins":newAdmins} }) And I'm getting a MongoError from the catch stating '\'$unset\' is empty. You must specify a field like so: {$unset: {<field>: ...}}' But it isn't empty. moderators, however, isn't in the schema, which is why...

Displaying only the title on the client returns undefined

javascript,mongodb,express,mongoose,ejs
I have a defined a schema in mongoosejs like this: var uploadSchema = mongoose.Schema({ title : String, happy : String, }); I want the data in my db to be displayed on the client (I am using ejs for templating): app.get('/yay', function (req, res, next){ Upload.find({}, function (err, course){ res.render('./pages/yay.ejs',...

Project array content with mongodb

arrays,mongodb,mongoose,coordinates,geospatial
My problem is that when I'm using MongoDB 2D index for coordinates everything works just fine but the JSON output is not what I desire. var schema=new Schema({ location:{ type:[Number], // [<longitude>, <latitude>] index:'2d', required:false } }); **desired output** { "_id":"xxx", "longitude":18.056974411010742, "latitude":54.31120601701069, } **what i get** { "_id":"xxx", "location":[18.056974411010742,54.31120601701069]...

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

node.js,mongodb,mongoose
Lets say I am using a $unwind on a field in mongoose schema According to the above link If field is not present then unwind will ignore input document How can I prevent that so that result of query is returned without unwinding process even if field is not present...

How to add extra parameters to a function callback

javascript,node.js,callback,mongoose
I am using a few callbacks in an app that I'm writing. I am using Mongoose models and need to save a few different places. The save function takes a callback, and the callback gets error and model for its parameters, but I'd like to send the callback an extra...

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

mongoose
This is the relevant part of the code that I think I'm getting the error in - it says "if (this.ended && !this.hasRejectListeners()) throw reason; TypeError: Object # has no methods 'updateMyField'" FieldSchema .post('save', function () { var self = this; self.updateMyField(); }); FieldSchema.methods = { updateMyField: function() { var...