Questions tagged [mongoose]

Mongoose, renowned as a prime ODM (Object Document Mapper) for MongoDB, is a cutting-edge JavaScript-based tool meticulously crafted to excel in an asynchronous setting.

Using a Mongoose.js model in a different folder without exporting it, and still being able to access its schema through requiring

I have a users.server.model file var mongoose = require('mongoose'), Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: String, username: String, password: String }); mongoose. ...

Updating a nested object within an array that is nested within an array of objects in Mongoose can be achieved by traversing

My MongoDB Locations collection contains two documents, each with its own array of confirmed bookings represented as objects with unique Ids. How can I update the object with _id: c1? Is there a way to achieve this in one query? [{ _id :63233022222222, ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchronous due to the ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman, all ...

Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered ...

Retrieving data from MongoDB and saving it to your computer's hard drive

I've asked a variety of questions and received only limited answers, but it has brought me this far: Mongoose code : app.get('/Download/:file(*)', function (req, res) { grid.mongo = mongoose.mongo; var gfs = grid(conn.db); var fi ...

Mongoose.js - working with arrays of geographical coordinates

Can you help me achieve the following structure? { event : "something", location : [ { long:25, lat:34 }, { long:25, lat:35 }, . . . ] } Is it possible to impleme ...

I'm curious why my express route functions properly when I write it first, but throws a cast error if I place it elsewhere in

One of the routes in my app involves a friend route that I have registered on the user route. The user route is also registered in the app. In the user schema, I have utilized mongoose.Types.ObjectId. Mongoose Version: 5.9.19 Within User.js: router.use ...

Updating multiple documents in mongoose using Node JS is a breeze

When attempting to update multiple documents using a query generated from an object array, I encountered an issue where only one document was actually modified. var split = num.toString().split(','); var list = new Array; for ( var i in split ) { var ...

Storing Many-to-One Relationships in Mongoose from Both Ends

I have recently started working with MongoDB and using Mongoose for my project. In my database, I have two models: users and recipes. User Model: recipes: [{ type: Schema.Types.ObjectId, ref: 'recipes' }], Recipe Model: _creator: { ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

The initial login attempt on the ExpressJS app is successful, but subsequent login history is

I recently created an application using ExpressJS, PassportJS, MongoDB with Mongoose, and JSON web tokens. When implementing the successful login route, I encountered the following code: await user.insertLoginTime(); const token = user.generateJwt(); res ...

A comprehensive guide on extracting matching date from MongoDB with Mongoose

I'm currently facing an issue with returning the appropriate records for a given date query in MongoDB and Mongoose. Despite my efforts, all rows are being returned instead. Below, you'll find the relevant code snippet as well as the model schema. Please ...

The moment the code throws an error, the Node local server abruptly halts

Within this code snippet, I am attempting to utilize findOne in order to locate and remove a specific dishId from my Favorites document. The code functions correctly when a valid dishId is provided. However, if an incorrect dishId is entered, the code will ...

What are some methods to display search outcomes in mongodb?

I have created a Comment Model with specific fields including userId, contentId, repliedTo, and text. The schema for the Comment Model is defined as follows: const CommentSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId ...

Error in Moongose: Using .populate on a key with whitespace is not functioning as expected

I am currently working with Express and Mongoose for database operations. I have encountered an issue where attempting to populate a path with a key that contains a whitespace causes it to be ignored. MongoDB Model: const OrgCrimeSchema = new Schema({ g ...

While the find operation in mongoose failed to return any documents, the compass tool was successful in retrieving them

Objective To retrieve products based on category id from the 'products' collection in MongoDB using mongoose.find method. Expected Outcome vs. Actual Outcome The expected result is to receive all documents matching the specified category withi ...

Aggregating MongoDB with project and unwinding an empty array

After encountering a similar problem to the one described by the author in this question, I found a solution provided by another user on Stack Overflow: Unwind empty array in mongodb However, after updating my MongoDB/Mongoose recently, I am now facing a ...

Encountering the error message 'db.get is not a function' in Node.js while working with MongoDB

Developing a voting application that involves creating two models: users and polls. The database will have two collections - one for users and one for polls. User.js 'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Use ...

Encountered an issue trying to access undefined properties in the mongoose response object

When utilizing the mongoose Schema in node.js, I have defined the following structure: mongoose.Schema({ name: { type: String, required: true }, userId: { type: String }, water: { type: Array }, fertilizer: { type: Array } }) Subsequently, ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

Trouble with Mongoose: New document not being saved in array

Here is the code I am working with: router.put("/add-task/:id", auth, boardAuth, async (req, res) => { const listId = req.params.id; try { const board = await Board.findOne({ _id: req.board._id }); if (!board) return res.status(404).send("N ...

Is it possible to create a chain of static constructors in Mongoose, similar to how scope works in

Can static constructors be chained in mongoose? In Rails, chaining named_scopes is the common practice. I have a unique request to fetch data from mongo, however sometimes I need to impose a limit or conduct a count on them as well. ...

The "offset" parameter has exceeded the acceptable range. It should fall within the range of 0 to 17825792

A critical error has occurred due to an unhandledRejection. It seems that a Promise rejection was not caught: RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of bounds. It should be >= 0 && <= 17825792. Current value is 17825796 at ...

Can Mongoose in MongoDB be used to create a real-time search function with Angular controller and form input text for search queries?

Apologies for any language errors and what may seem like a silly question to some, as I am new to programming in Angular, Node, Express, and MongoDB. My query is if it's possible to implement real-time search functionality in the database. I want to ...

Can you guide me on how to display data in expressjs using mongoose?

Recently I started working with mongoose and I'm attempting to retrieve data from my mongodb using mongoose. Below is the code snippet I am currently using: mongoose.connect('mongodb://localhost/dbname'); var Schema = mongoose.Schema; var dbSchema = new S ...

Executing a recursive function synchronously in Node.js using call function

I am currently working on a MEANJS project and have a function that returns an array by fetching data recursively. However, I am facing difficulty in figuring out how to access that array. The Issue:- Let's say we have users A with properties {_id:'001', ...

Unable to utilize $regex for searching by _id in Mongoose version 6.6.3

My attempt to search data by id is as follows: _id: { $regex: '63a1bda46ec7f02cf5e91825', $options: 'i' }, }) .populate('user', 'name') .sort({ updatedAt: -1 }); Unfortunately, this r ...

NodeJS throws an UnhandledPromiseRejectionWarning when I handle an error

I am looking to address the issue that arises when a user deliberately enters an incorrect objectId. However, I encountered an error when compressing the error into a function called check objectID: UnhandledPromiseRejectionWarning: Error: INVALID_ID Here ...

Iterate through a Mongoose object with a for loop to access a nested array and retrieve a specific property from an

As someone who is new to JavaScript, I have a question regarding using Mongoose. Why am I encountering an error when trying to access a property with a for loop? The schema I am working with contains embedded schemas. Usr.findOne({numCli: req.body.numTar ...

Searching for all documents containing a specific keyword in MongoDB can be done by using the $

Experimenting with Mongo DB's built-in search functionality using text indexes, I am trying to retrieve all documents that contain a specific keyword. However, the output I receive is not as expected: Cursor { // Output details here } I am looking for ...

adding new data to an array of objects in mongodb and maintaining its integrity

Seeking assistance in creating a voting system that involves an array of objects containing user IDs and their corresponding vote values. If a user has previously voted but wants to change their rating, the goal is to update the rate value in the array fo ...

Organize complex data retrieved through mongoose filtering with a deep nesting, in a

I am currently using mongoose filter to extract nested data from a MongoDB document. I am looking for guidance on how to efficiently sort the results and if there are any better methods or resources available (Please suggest some solutions or references if ...

What is the most effective way to retrieve the top five maximum results from a sub document using

I am relatively new to using mongo db and although I have a basic understanding of it, I still have some questions. Below is a collection of albums that I currently have: { "_id" : ObjectId("5f9ff607562cdb1c5c2acb26"), "t ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is powere ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' event ...

Mongoose is throwing an error and saying that save() is not a valid function

exports.clearHours = (req, res, next) => { Hour .find({ user: req.body.userId }) .then(hour => { for (let i=0;i<hour.length;i++) { hour[i].hours = 0; } return hour.save() }) .then(result => ...

Issue with sequence in NodeJS, Express, and MongoDB using Mongoose not functioning as expected

I am attempting to create a collection using auto increment numbers in the _id data, but it just says "Sending request" and I don't have a callback in this call. I'm really not sure why it's not working "mongoose": "^7.5.3" "mongo ...

Enhancing multiple documents in mongoDB with additional properties

I am working with a data structure that includes user information, decks, and cards. I want to update all the cards within the deck named "Planeten" by adding a new property. How can I achieve this using a mongoose query? { "_id": "5ebd08794bcc8d2fd893f ...

Enable the upsert option in MongoDB Mongoose Collection.findAndModify: true

I'm currently working on implementing a user-to-user messaging feature within my NodeJS, Express, MongoDB application. The approach I'm taking involves utilizing two MongoDB documents: 'Messages' to store individual messages and 'Conversations' to group r ...

Leverage the power of grunt and mocha by incorporating a test database

I am creating a web application in Node.js, Express, and MongoDB with the help of Mongoose. I aim to set up a separate database specifically for running my Mocha tests using Grunt, in order to prevent any potential interference with the development databas ...

Navigating multiple databases while managing a single model in Mongoose

I am looking to create a system with 50 arbitrary databases, each containing the same collections but different data. I want to use a single Node.js web application built with ExpressJS and Mongoose. Here is a simplified example: In this scenario: The ...

Storing Profile Images Efficiently with NodeJS and Mongodb

Imagine I am in the process of developing a website that allows users to sign up, log in, and view each other's profiles. The functionality for registering, logging in, and viewing profiles has already been implemented. However, I am unsure about how ...

EJS: Is there a way to display multiple populated collections from mongoose in EJS file?

Having trouble rendering multiple populated collections from mongoDB in EJS. To provide more context, I'll share snippets of my code: models, routes, and views. Model Schema var mongoose = require("mongoose"); var playerSchema = mongoose.Schema({ ...

Unable to resolve the circular dependency issue with mongoose schemas

I am dealing with 3 models: Book, Author, and 'Category'. An Author can have multiple books, a Category can have multiple books, and a Book cannot be created without a valid Author or Category. const schema = new mongoose.Schema( { title: dbHelpers. ...

Tips on extracting value from a pending promise in a mongoose model when using model.findOne()

I am facing an issue: I am unable to resolve a promise when needed. The queries are executed correctly with this code snippet. I am using NestJs for this project and need it to return a user object. Here is what I have tried so far: private async findUserB ...

I am unable to retrieve the req.body or the body content in a post request. The code functions properly when using hardcoded JSON

Take a look at my code: controllers/task When testing in Postman, I'm getting validation errors I've even tried using a body parser, but it doesn't seem to be working either. Check out app.js ...

Exploring the capabilities of Mongoose with nesting documents and seamless read/write operations

A puzzling situation has arisen that is truly testing my patience. It should be a simple task, I hope. All I want to do is reuse a model in an array, like a recursive model definition. Here is the model in question: var mongoose = require("mongoose"); va ...

Unable to retrieve the userID from the express session

Trying to capture the user ID from the current session in order to create a delete profile function using express with express-sessions, mongoose, and passport. The code I'm using for deleting a user is functional. When manually inputting IDs from Mo ...

Issues with installing mongoose on Windows 7 using npm

Struggling to set up mongoose on Windows 7, I've exhausted all resources on Stack Overflow related to my issues with no success. Upgraded npm version to 2.4.1 If anyone can offer assistance, it would be greatly appreciated. Here is the error log: From I ...

Array of mongoose objects

Struggling to store an array of objects in mongodb using mongoose and node, I am facing challenges with simple validation. I have defined a Schema and a custom validation function as follows: const mongoose = require("mongoose"); const fieldsSch ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Accessing a dynamic property within an array of objects in Mongo/Mongoose: A complete guide

When using the $in operator within a condition, I am able to make it work by hard coding the property that I am searching for. However, I am unsure of how to handle this if the property is dynamic (I am iterating over an object where the key's value is an ...

The mongoose query appears to be functional in the mongo shell but is experiencing difficulties within a Node.js

Trying to retrieve a list of todos based on the 'userId' associated with each one is proving difficult. The code below does not return any rows: DB.TodoTable.find({ "userId" : ObjectId("54c12f5f3620c07019e6b144") }, function(err, todos) { if (err) ret ...

Exploring the Potential of Express and Mongoose through Mocha Testing

I'm currently experimenting with testing my REST API endpoint handlers using Mocha and Chai. The application was developed using Express and Mongoose. Most of my handlers follow this structure: var handler = function (req, res, next) { // Process the ...

Is there a way to verify if the password entered by the user matches the input provided in the old password field?

I am trying to compare the user's password with the one entered in the "oldPassword" input field. The challenge is hashing the input from the "oldPassword" field for comparison. How can I achieve this? Please review my ejs file and suggest improvements. Th ...

While the Mongoose aggregate query is functioning properly in MongoDB, I am encountering difficulties in converting it to a Mongoose

Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...

What is the best way to designate a default image when no image is selected in a form submission?

I have a CRUD application created using node.js, express, and mongoose. Within this app, there is a form with a file input for uploading images. I am utilizing cloudinary, cloudinary storage, and multer to manage these image uploads. When a user adds an im ...

Discovering Sub-Documents based on Criteria using Mongoose and MongoDB

Below are the descriptions of two Mongoose schemas : EmployeeSchema : var EmployeeSchema = new Schema({ name : String, employeeDetailsId: { type: Schema.Types.ObjectId, ref: 'employeedetails' } }); EmployeeDetailSch ...

Mongoose reverse population involves querying a document's references

I am currently exploring ways to populate my business orders using the businessId property in my orders collection. I attempted a solution but I am facing difficulties making it work. https://www.npmjs.com/package/mongoose-reverse-populate If you have an ...

Error in updating property values within an array with Mongoose

These are the Schema Details export const publicTaskSchema = new Schema({ task: { required: true, type: String }, user: { _user: { type: String, required: true }, userName: { type: String, required: true }, }, likes: { users: [{ ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

The passport authentication fails with the error message "Incorrect password" even before triggering the passwordMatch function

This situation is quite odd. My Objective I am attempting to set up an authentication server in node.js using Passportjs local strategy and JWT. This will allow users to register with an email and password, where the passwords are hashed using 'cryp ...

Field not found in result of mongoose query

Currently, I am exploring the use of node in conjunction with the express framework and utilizing mongo as a database. The schema that I have defined looks like this : var JsonSchema = new Schema({ ...

Session is being established by Express/Passport, however, the cookie is not being transmitted to the

Currently, I have a project running with React on the client side and Node.js on the server side. Client side (React app) - http://localhost:3000 Server side (Node.js) - http:..localhost:5000 My focus at the moment is on implementing user authentication ...

Connecting to a MongoDB or Mongoose database dynamically using Node.js

I am currently working on developing a multi-tenant application where each client will have its own dedicated database. Here is my scenario: I have created a middleware that identifies the client based on their subdomain and retrieves the necessary datab ...

Remembering checkboxes labeled as arrays

Below is the code snippet I am working with: router.post('/expenseReport', ensureAuthenticated, async (req, res) => { try { const{ startDate, endDate } = req.body; var expenseArray = []; var count = 0; var ...

Is it possible to add a sub-document to a specific parent document by using the parent's ID and providing the name:value pair for

Is there a way to update an embedded document by finding the parent using the _id? I need help with the correct syntax for locating the parent by _id and the sub-document by the username field: Models.Message.findById(req.params.message_id, { "to.usernam ...

Exploring the power of Bacon.js and RxJS in combination with Express.js and Mongoose.js

Currently, I have integrated Bacon.js into my server-side application using Express.JS (version 4.x). However, I am encountering an issue where the method does not respond at all. Can anyone help me figure out what might be causing this problem? var User ...

Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

a guide on utilizing nested populate with node.js and mongoose

I am currently working on the Populate method in Mongoose. Here is my query: await User.findOne({_id: req.params.userId}).populate({ path: 'review' }).then(result=>{ console.log("here" + result) if(result && r ...

Should I share a single DB connection throughout the entire app or establish a new connection to the DB for each request?

I am currently working on developing an API using Nodejs and Restify. My database of choice is MongoDB, with the use of Mongoose. One question that has been on my mind is whether it would be better to share a database connection throughout the entire appl ...