Questions tagged [mongoose]

0

votes
1

answer
7

Views

One out of two Document property not inserted in a mongoDB collection using: Mongoose and ExpressJS

A Nodejs server application gets Name and Age from an HTML form (with post method) and with the help of ExpressJS and Mongoose has to create a MongoDB document. That works but Age is not written in the document of the collection. Please help me to fix it. Here are the files with the code: personform...
user374324
1

votes
3

answer
202

Views

How to load asynchronous database url and initiate database connection before express.js app starts?

I have configured the express.js app to run on AWS lambda. The database URL is stored and encrypted in the Amazon KMS service so if I want to use the URL then I have to decrypt the key using AWS KMS service. // imports import mongoose from 'mongoose'; import serverless from 'serverless-http'; // KMS...
sym
1

votes
1

answer
1.9k

Views

NodeJS, get return value from async await

I have an async await function that uses mongoose: const createModelB = async (id) => { try { let user = await User.findOne({id: id}); if (user) { let modelB = new ModelB({ user_id: user.id }); modelB = await scrum.save(); return modelB; } return null; } catch (err) { console.error(err); } return nu...
Mr.D
1

votes
1

answer
811

Views

Can't connect to mongo docker image with mongoose

I'm trying to run a simple docker setup with node and mongo: Dockerfile: FROM node:8.9.4-alpine RUN mkdir /app WORKDIR /app COPY package.json /app/ COPY package-lock.json /app/ RUN npm install ADD . /app/ docker-compose.yml: version: '3' services: db: image: 'mongo' ports: - '27017:27017' api: build...
Philip Feldmann
1

votes
1

answer
233

Views

TypeError: callback.apply is not a function after allowDiskUse

I have a collection having 1Million documents... I have passed the option for allowDiskUse and now it is throwing error TypeError: callback.apply is not a function I have searched for this but could get the solution... Please help const pictures = await Picture.aggregate([ { $sort: { createdAt: -1 }...
Anthony Winzlet
0

votes
0

answer
4

Views

How to change property of newly created collection on click

I am creating a new collection from current schema with same properties. I am using nodemailer to verify email by setting a schema key to value true upon clicking the link. It is happening successfully if changing value of current schema from this code:- router.get('/verify',function(req,res){ con...
NoobCoder
1

votes
1

answer
78

Views

MongoDB one-to-many - array of IDs or ID ref on child model? [closed]

Specifically, I'm thinking of a chat app, where a User has many Chats and each Chat has many Messages. How would I express the Chat --has-Many--> Message relationship? Initially, I thought I'd store the list of Message ID references on Chat, e.g. a Chat document could look something like { _id: Obje...
Code Jockey
0

votes
0

answer
6

Views

TypeError: Cannot read property 'findOne' of undefined from Passport

I have implemented a Passport login feature in Node.js. I try to log in using LocalStrategy, but I get an TypeError: Cannot read property 'findOne' of undefined. I think there is a problem with findOne in the async try part of LocalStrategy.js. But I do not know what the problem is. Is there somethi...
COLEAN
1

votes
1

answer
212

Views

mongoose virtuals with typescript error - The containing arrow function captures the global value of 'this' which implicitly has type 'any'

I am trying to use mongoose virtuals with typescript. And not able to make it work. I get error related to using this in the code. I checked many references but could not find a reference to make this work. '[ts] The containing arrow function captures the global value of 'this' which implicitly has...
Dhaval Chokshi
1

votes
2

answer
27

Views

Correct way to figure out what rejection a promise had?

I have an API / express router: router.post('/signup', async function (req, res) { try { var user = await controllers.user.register(req.body.username, req.body.password); req.session.user = user; res.json(user); } catch (e) { res.status(500).json('DB Error'); } }); Currently, on error, it returns 50...
user2719875
1

votes
1

answer
193

Views

TypeScript - mongoose - document middleware compilation error

Issue I just installed TypeScript 3.4 and noticed that some of my Mongoose middleware functions were no longer valid TypeScript. TypeScript output model.ts:19:8 - error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. 19 this.modified = new Date...
maxpaj
1

votes
3

answer
18

Views

How to query a document with the highest value of a field

Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below. I want to get the document with the greatest value of 'id'. Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find...
lakers5824
-1

votes
0

answer
4

Views

Mongoose/Mongo: A query to find all documents older than five minutes?

I need mongoose to run a query that finds documents older than an amount of time described in milliseconds found in the config folder. This amount of time is stored like this, keys.anAmountOfMilliseconds Thus far, I've been able to pull all documents created in between NOW and FIVE minutes as descr...
ThirdGhostHand
1

votes
0

answer
6

Views

Can't find a document from MongoDB by ref id

I have a member in my application like so const member = new Schema({ name: { type: String, required: false, }, organization: { type: Schema.Types.ObjectId, ref: 'Organization', required: true, }, }); I struggle to find a member by organization id. Even if I first find a member by id using the follo...
P_Andre
0

votes
0

answer
8

Views

MongoDB/Mongoose: A query to find documents older than an amount of milliseconds?

I need to find and manipulate all documents older than a certain time. I'm quite lost as to how this query is supposed to be written. I understand that Mongo's ObjectID has a byte describing a document's time of creation, but I haven't yet figured out how to capture all data older than a specific am...
ThirdGhostHand
1

votes
1

answer
456

Views

Remove object attribute with array map

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; });//element...
reggie
1

votes
2

answer
11.9k

Views

TypeError: next is not a function

I'm running a Node.js-server and trying to test this Rest API that I made with Express. It's linked up to MongoDB using Mongoose. I'm testing the individual routes using Postman and I get an error when trying to send a PUT-request to this route: // PUT /meetings/:id // Route for editing a specific m...
SudokuNinja
0

votes
0

answer
6

Views

Using MongoDB User to log into application

I set up my mongoDB to take in a user with a userID, password, firstName, lastName, email. This user needs to be able to login to my application and have it's own session to add and remove items from a store. I cannot get this user to sign in. I do have my sign-in page working and it is accepting v...
teewrecks
1

votes
2

answer
40

Views

How to ensure sequential execution of nodejs in order to return a result from a query?

I'm very new to nodejs and javascript in general. I'm trying to implement a response from a controller method which will return a result from a query. Currently, the response is sent before the query is finished. Would really appreciate some advice on how to approach this. I've tried implementing a...
an.n
1

votes
3

answer
42

Views

mongo db - efficient way to search strings

I am looking to search strings that are broken up into a prefix, numbers and letters, I currently need to search 55 million rows and a row looks like this (I also save a concatanated version of the entire string): { 'prefix' : 'AA', 'numbers' : '02', 'letters' : 'AFO', 'code' : 'AA02AFO' 'price' :...
berimbolo
1

votes
3

answer
43

Views

Mongo ISODate - how to check if 30 or more days passed? [duplicate]

This question already has an answer here: Find all documents within last n days 2 answers Struggling with creating a condition to check if 30 days have passed since specified ISODate in mongo. The field name is creationDate, Im using find function, and I want to find only these, where 30 days have...
Patrickkx
0

votes
2

answer
20

Views

How to find documents inside ref object without an id?

I have two documents in mongodb: export const Category = mongoose.model('Category', new mongoose.Schema({ name: { type: String }, })); export const SubCategory = mongoose.model('SubCategory', new mongoose.Schema({ name: { type: String }, category: { type: mongoose.Schema.Types.ObjectId, ref: 'Catego...
Jon Sud
0

votes
2

answer
13

Views

Exclude _id field from JSON response Node js

I want to exclude default _id field while fetching the data result from JSON API in my node-express app. I tried several ways to do so but still the data shows _id in GET response. Here are some of the ways I figured out that didn't worked: exports.get_all_clothing = (req, res, next) => { Clothing.f...
bubble-cord
-1

votes
3

answer
102

Views

Can not add additional element to (mongoose) object

I have a nodejs express application with an api to return data from a mongodb database. This is my mongoose model: const bookingSchema = new mongoose.Schema({ timestamp: { type: Date, default: Date.now, required: true }, tags: { type: [String], required: true }, amount: { type: Number, required: tru...
mles
1

votes
0

answer
88

Views

How do I get rid of BSON objects after a mapReduce?

I'm a complete beginner to map-reduce and relatively new with MongoDB. I am trying to perform a map-reduce on a collection (by the name Customers). My map function: var map = function() { emit(this.nationality, {edad: this.age, telefono: this.phone_number}); }; My reduce function: var reduce = funct...
1

votes
1

answer
17

Views

Mongoose and nested arrays

My Schema let citySchema = new mongoose.Schema({ ... }); let countrySchema = new mongoose.Schema({ regions : [{ cities : [ref: 'City'] }] }); The problem - how to insert existing city into a selected (by _id) region. The _id of a region is automagically added by mongoose/mongodb, and I do not want t...
Chris
1

votes
2

answer
54

Views

How to remove an element from an array within Mongo

I'm completely stuck with Mongoose and remove method. I have a page with comments and form with a button Delete. My goal is to delete only that comment which was clicked. Below is my MongoDB file (By the way I use method override of the express library to handle both request post and delete). { '_i...
Ar2zee
1

votes
1

answer
194

Views

Wait for save before continuing with the function

I have a loop which loops through an array of users, this loop is asynchronous, what I want to do is for every user create a new document and save it and wait for this to save and then move on to the next user. I am able to handle when to move on to the next user, so my problem is while saving the n...
Muhand Jumah
1

votes
2

answer
135

Views

Mongoose populate where

I have two models - M1 and M2. In M1 I have an array of M2 objects. I'm trying to create a query that will grab a bunch of M1 models but ONLY if a certain field in M2 matches the criteria I set. I've setup the models correctly (so M1 has an array of Schema.Types.ObjectId for M2). Ideally I'd want t...
user1157885
1

votes
0

answer
107

Views

Accessing Object inside of Mongoose Field

I am trying to create a new user using mongoose and express. I am attempting to add a profile picture to the users Schema. I already have everything working, with the exception of the profile picture. I do not know how to access the buffer and contentType properties for the Schema.
Ellington Crevier
1

votes
1

answer
165

Views

How do I also delete the ObjectId from the parent element with mongoose?

So essentially what I have is a location index. Here is the location schema: var locationSchema = new mongoose.Schema({ name: String, gps: String, image: String, description: String, catches: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Catch' } ] }); In this schema I also have 'catches' essenti...
Ronald Long
1

votes
1

answer
78

Views

How to create auto increment ID in mongoose (Node js) other than _id

For Example on saving user userId value has to be something like U1001, on adding another record userId of that record has to be U1002
Nathash
1

votes
2

answer
51

Views

NodeJS+Mongoose - Need help Refactor code using Promises

Consider this example : router.post('/', function (req, res, next) { var order = new Order({ customer_id: req.body.customer_id, order_elements: [] }); order.save(function(err, saved_order) { var elementsSaveCount = 0; req.body.order_elements.forEach( function(order_element, index) { orderElement = n...
Nite
1

votes
0

answer
310

Views

MongoDB - Problems with database design and statistical data calculation

I am currently facing a problem with MongoDB and that's probably due to my schema design, but I am unsure how to go about it. So basically I have this collection (mongoose Schema): const PlayerStatsCollection = { sportType: MongoId, player: MongoId, match: MongoId, team: MongoId, date: Date, league:...
Morphex
1

votes
1

answer
318

Views

Mongoose query returns empty array

I'm using Express to do a find operation in a Mongo collection and return the result. I know that there is data in the collection, but the result array comes back empty. I suspect that it's an issue with the schema, but can't figure out what. Thoughts? Route: const PlotStatus = require('../models/pl...
Boris K
1

votes
1

answer
34

Views

How to update a MongoDB collections with an unknown number of possible fields using Mongoose

I want to update a mongodb collection without knowing exactly how many and which fields will be used to update. For example, if I have a user and they update information about them on different pages then it will not always be the same fields that are updated. Below is my current idea for how to app...
Brandon
1

votes
2

answer
76

Views

MongoDB Aggregation by Name and Different Time Interval

I've been looking for a solution for several days, and I can not get a result. Please, help me! I have a data in MongoDB: { name: 'apple', date: 2018-01-04T10:00:00.000Z, price: 100 } { name: 'apple', date: 2018-01-04T10:01:00.000Z, price: 101 } { name: 'apple', date: 2018-01-04T10:02:00.000Z, price...
COS
1

votes
1

answer
80

Views

Passing REST URL parameter as query condition in Mongoose

Newbie in nodejs/mongoDB here. I've tried, with no success, to find the answer to my problem before posting here. I'm creating a simple node RESTAPI get services with Mongoose. I'm trying to pass the field value of the collection to retrieve a specific document. Like this http://localhost:3000/in...
bmdinesh
1

votes
0

answer
41

Views

MongoDB / Mongoose: aggregate - need to query on date range

I have a similar issue to a previous one I had: Mongoose aggregate, can't dynamically add someField: { $not; null } I am trying to perform a query on a date range. This is my attempted syntax, which is wrong (and throws same kind of error as stated in the previous issue): if (typeof dateBeginning...
Jeff Matthews
1

votes
0

answer
17

Views

Mongoose weird error duplication in array of subschemas

I'm testing a couple of schemas using mongoose and I'm getting the same error twice on a subschema. This is my model: const OrderSchema = new Schema({ email: { type: String, required: true, validate: isEmail }, order_code: { type: String, unique: true }, status: { type: Number, required: true }, pro...
Efemorav

View additional questions