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. ...
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, ...
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( ...
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 ...
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 ...
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 ...
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 ...
Can you help me achieve the following structure? { event : "something", location : [ { long:25, lat:34 }, { long:25, lat:35 }, . . . ] } Is it possible to impleme ...
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 ...
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 ...
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: { ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 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 ...
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 ...
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. ...
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 ...
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 ...
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 ...
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', ...
My attempt to search data by id is as follows: _id: { $regex: '63a1bda46ec7f02cf5e91825', $options: 'i' }, }) .populate('user', 'name') .sort({ updatedAt: -1 }); Unfortunately, this r ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 { ...
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 ...
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 ...
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 => ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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({ ...
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. ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...
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 ...
Below are the descriptions of two Mongoose schemas : EmployeeSchema : var EmployeeSchema = new Schema({ name : String, employeeDetailsId: { type: Schema.Types.ObjectId, ref: 'employeedetails' } }); EmployeeDetailSch ...
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 ...
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: [{ ...
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 ...
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 ...
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 ...
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({ ...
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 ...
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 ...
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 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 ...
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 ...
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 ...
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 ...
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 ...