FAQ Database Discussion Community
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; });...
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,...
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));...
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...
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...
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:...
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?...
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' :...
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...
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)...
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...
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...
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({...
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) {...
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...
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) {...
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?...
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...
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...
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...
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...
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.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...
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?...
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);...
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...
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...
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...
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...
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...
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...
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,...
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...
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...
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,...
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'); });...
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...
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...
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...
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},...
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'));...
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
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...
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...
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...
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" :...
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...
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...
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 :...
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...
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.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...
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 } ...
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...
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...
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...
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...
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...
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....
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...
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...
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]...
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...
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...
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...
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...
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...
javascript,date,mongoose
My Mongoose date query return the below string: 24th Jun 2015 How to convert it to javascript date object?...
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...
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) }); }...
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...
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...
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 );...
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...
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...
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": []...
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,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({...
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',...
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)...
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...
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...
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...
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.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...
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...
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...
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 |--...
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?...
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...
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...
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...
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....
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...
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...
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,...
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:...
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}); ...
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" :...
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... ...