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.

Node.js application freezes when a page is refreshed

What could be causing a request to hang indefinitely after refreshing the page and making a new request? How can I troubleshoot this issue? Here is a snippet of my code: if(params are not good){ res.status(500).json("Invalid date."); }else{ doDat ...

Utilizing API calls to sort data by specific columns in Mongoose, NodeJS, and Express

Currently in the process of developing an API for a cooking application. I have created a model called Recipe and now want to incorporate sorting functionality based on the specified parameter in the request. I am looking to sort the data by any column pr ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Exploring MongoDB API Pagination

Picture a scenario where a customer has a list of items with a limit of 10. When they need the next set of 10 items, they send a request with a skip of 10 and a limit of 10. However, what if some new items were added to or removed from the collection sinc ...

Encountered an issue while attempting to launch the express

I've encountered an error while attempting to launch my express server, and despite my best efforts, I can't seem to figure out the cause. It was operational for a period of time before suddenly ceasing function, though I'm unable to pinpoint any changes t ...

Trying to invoke a specific middleware in NodeJS using Express and Mongoose within one another

I am struggling to reuse some code in two separate NodeJS controllers, and it seems like I'm having trouble understanding how the function calls work. The data is coming from a MongoDB using Mongoose. When I call the findMyBoatPictures code on its own, ev ...

Locating terms within two attributes of a MongoDB record

Searching for a word from two properties, 'firstname' and 'lastname', in a document has been challenging. The current code is not providing the expected response when searching through multiple properties. As a beginner in mongo db, I would appreciate some ...

Filling Mongoose models with interconnected data

I've spent the past 4 hours trying to resolve this issue with no success. I have 3 Models set up in my code: The first Model is for Tournaments: var tournamentSchema = mongoose.Schema({ tournamentName: String, nrOfPlayers: String, players: [{ type: mon ...

When breaking down code in models, Node.js may display a `var undefined`

As I embark on my journey of creating my first nodejs app, I encountered an error when attempting to transfer a portion of my code to an external JavaScript file. The specific piece of code I am trying to move is the mongodb schema declaration: var mongoo ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

The collaboration of React hooks, typescript, mongoose, express, and socket.io in perfect harmony

I am currently working on setting up a frontend React app to communicate with a NodeJS Express API using socket.io import React, { useEffect, useState } from "react"; import io from "socket.io-client"; const socket = io("http://lo ...

The latest entries are not visible on Mongoose unless the page is refreshed

There is a router with handlers for GET and POST requests related to documents. When creating new documents and posting them, the redirection works smoothly. However, upon initial page load after creation, only existing documents are displayed. It's only ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

The object array in Mongoose efficiently stores duplicate date and time values

Here's an example of my mongoose schema: const clothesSchema = new mongoose.Schema({ clothes: [{ _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Clothes' }, dateAdded: { type: Date, default: Date.now } }] }); ...

Creating a one-to-many relationship in Mongoose using array push operations

I have two collections: Projects and Developers. I can assign a single project to a developer, but I'm struggling with assigning multiple projects. Any suggestions on how to achieve this? Would using an array be the best approach for assigning multiple pr ...

Is express-jwt assigning the user object to req.user._doc, as opposed to just req.user?

Previously, I have utilized the npm package express-jwt for effortless JWT signing and decoding. Typically (and as per the documentation), it decodes the token in a request, extracts the user object payload, and assigns it to req.user. However, this time a ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

Guide to using Node.js to efficiently add documents to several collections in a single query

I am exploring the possibility of inserting documents into multiple collections with a single query. Let's say I have two collections named person and address. My goal is to insert documents into both collections using just one query. Specifically, d ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Tips for accessing subdocument data from Mongoose in the frontend using ReactJs

I am looking to retrieve comprehensive information about a collection known as "commercant", which includes another collection called "personne" in the front end using ReactJs. Although Postman returns all data, the front end is struggling to interpret the ...

The specified data type is Schema.Types.ObjectId, and it triggers an error stating "ReferenceError: Schema is not

As I was creating a database schema and trying to reference the userschema, I encountered an issue while writing the following code: postedBy: { type: Schema.Types.ObjectId, ref: 'User' }, type: Schema.Types.ObjectId, ^ ReferenceE ...

Error: The database query returned duplicate results while using ngRepeat

I have encountered a persistent error that seems to be related to the "fetchCourses()" function in courses.js. Despite various attempts, the error persists and only goes away when I comment out this particular function. My suspicion is on the HTTP request, ...

Implementing various functions on a Mongoose Model Object

Using Nodejs Expressjs MongoDB and Mongoose, I am developing a REST API for a small service app. All routes are created with simple functions like .find() or .findOneAndUpdate(). For example: router.get('/testTable', function(req, res, next) { ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Encountering an issue when trying to install Mongoose via NPM with the error message "Error: gss

Upon executing npm install mongoose --save, a WARNING is generated while working on El Capitan 10.11.1, Xcode 7.1.1 Build version 7B1005, and npm 2.14.7. Although the operation appears functional at the moment, I am curious to delve deeper into this issu ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...

Tips for connecting files in mongoose

I recently started working on developing with Express and decided to create a blog. I have set up two models for posts and users. In the user schema, there is an attribute called 'posts' where the post will be saved when a user creates one. In th ...

What is the proper way to gracefully stop a koajs server?

Is there a way to gracefully stop koajs like I've seen for expressjs? I also need to disconnect database connections during the process. Specifically, I have a mongoose database connection and 2 oracle db connections (https://github.com/oracle/node- ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Troubleshooting: Express router does not correctly implement Mongoose's findByID method when using URL route

After following a tutorial, I encountered an issue with the code: /* GET one item. */ router.get('/items/:id', (req, res) => { Item.findById(req.param.id, (err, items) => { if (err) res.status(500).send(error) res.status(200).json(items); ...

The mongoose library fails to identify the collection based on its name

Here's my modified code: var mongoose = require('mongoose'); var db = mongoose.createConnection('localhost', 'bttf'); db.once('open', function() { var schema = new mongoose.Schema({ name: String, age: Number }); var col = db ...

Encountered an issue when trying to connect to an established Mongoose connection using MongoStore - Unfortunately, it seems there was a TypeError due to being unable to read

I am facing an issue while attempting to save my express-sessions on cloud.mongodb using the existing connection with mongoose. The problem arises when I pass mongoose.connection as a parameter of connection to new MongoStore({mongooseConnection:mongoose. ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

What is the best method for inserting data into multiple databases simultaneously in MongoDB?

As a beginner in the Mean Stack, I find myself in a scenario where I require assistance in uploading data to various databases through mongoose. Any guidance on this matter would be greatly appreciated. ...

Saving base64 data directly to a mongoose database in an Express.js server can be achieved by

I am facing a challenge where I need to store an image directly in my database instead of on the server. Here is the model I am using: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var categorySchema = new Schema({ img: { data: ...

Combining arrays of Mongoose ObjectIds with Lodash union

I've encountered an issue with 2 arrays that contain ObjectId items: array1 and array2. My goal is to generate a union of the two arrays. To achieve this, I utilized the following code: let res = _.union(array1, array2); However, the resulting res ...

Retrieve data with Mongoose by searching for a specific value within an array of objects using a find query

I am trying to create a query that functions in the following manner: model.find({'UDID': { listOfobjects[i].UDID }}) I understand this syntax is not correct, but my intention is to iterate through all objects in the array and reference the UDID property ...

Math.eval Support: The function may exhibit sporadic behavior, occasionally functioning properly and occasionally

Just dipping my toes into the coding world and currently working on a web app that's like a dashboard. I'm using node js, express, and mongoose. I've set up my schemas and collecting user data. There's some data I need to crunch number ...

Headers cannot be set once they have already been sent in NodeJS

Here is the code where I authenticate users in a group, push accounts into an array, and save them using a POST request on /addaccount. groupRouter.post('/addaccount', Verify.verifyOrdinaryUser, function(req, res, next) { Groups.findById(req.body.group, f ...

Error encountered when attempting to populate nested fields in Mongoose

Recently, I encountered an error while trying to add comments to my posts by using nested populate for mongoose. Initially, everything was working fine when I only pre-populated user data. However, as soon as I implemented nested populate, I started receiv ...

Determine the total sum of sub documents in MongoDB using Node.js

In my collection structure, I have the following data: [{ "_id": "....", "name": "aaaa", "level_max_leaves": [{ level: "ObjectIdString 1", max_leaves: 4, }] }, { "_id": "....", "name": "bbbb", "level_max_leaves ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Information. 'Error: ', err ...

Errors from Mongoose do not get propagated from the router to the app layer

There is a single API application set up like so: const express = require('express') const app = express() const router = require('express').Router() ... route.post('/dogs', (req, res, next) => { const dog = new Dog() // defined in the actual applica ...

Struggling with inserting data into MongoDB within my MERN application

I am currently developing a MERN app that allows users to create tasks and collaborate with others. To start my backend, I ran the nodemon index.js command in the git bash terminal. However, every time I try to send POST requests for data, I encounter an e ...

Avoid encountering a mandatory field error when utilizing the save() function

I am currently enrolled in a course that is outdated, and unfortunately, there is no one available to answer my questions. I'm hoping the information provided will suffice. I have a concern about not receiving a required field error when using the save( ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require('config'); const { check, validationResult } ...

Searching for nested sub documents in Node.js using Mongoose

I have a schema structure as follows: const propertiesSchema = new Schema({ name: { type: String, required: true }, shortDescription: String, totalArea: String, address: { type: mongoose.Schema.Types.ObjectId, ...

Failed authentication error with Node, Express, and Mongoose

I've recently started diving into Node, Express, MongoDB, MLab, and backend programming as a whole. I'm currently facing an issue while trying to submit a post request to an MLab database. It seems like the problem lies within Mongoose and MLab i ...

Error message: "No schema found for model 'User'.Create a schema using mongoose.model(name, schema)" with identifier 'MissingSchemaError'

I have been working on developing a schema for a user authentication system but keep encountering the error message mentioned above. I recently created two new pages with the code provided below: Users.js var mongoose = require ('mongoose'); var crypto = ...

Pagination in Mongoose implemented on the server side

I am currently working on implementing server side pagination in a NodeJS, Express, and MongoDB API. The API relies on mongoose to interact with the database. I am struggling with customizing the response from the Controller. Model: const mongoose = requ ...

Does Model.find() in MongoDB return an object or an array of objects?

const trips = await Trip.find() After using console.log(typeof trips), it displayed 'object' in the console log. However, when I used console.log(trips), it showed an array of objects. This has left me slightly puzzled about what is actually bei ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

Having trouble grasping the concept of ASYNC series within the ASYNC npm package

Hey there! I'm looking to eliminate the chaos caused by ASYNC OF HELL in my API. While searching for a solution, I stumbled upon an npm package called async that offers a feature known as async series. Excited to try it out, I implemented it in my API ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

Retrieve the first and last name from the stored full name in MongoDB using Node.js

Currently, I am exploring how to extract the firstName and lastName from a FullName for educational purposes. However, when attempting to run this application, I encounter two errors: a) Mongoose Schema Student has a 'firstName' virtual b) Mongoose Schema ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows: https://i.stack.imgur.com/YgFjd.png The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds whi ...

Saving an embedded document within another document in MongoDB using Mongoose

Our project requires us to save a duplicate of a Mongo document as a nested subdocument in another document. This copy should have a direct link to the original document and needs to be a complete replica, like taking a snapshot of the original data. The ...

I'm looking to implement a feature in my notes application built with the MERN stack using Mongoose for MongoDB that allows users to add hidden notes. How

I am looking to implement a hidden notes functionality in my web application. When the "hide note" button is clicked, I want the note to be removed from its current location and added to a hidden notes section. Users should then have the ability to view an ...

Issue with Mongoose pre-update hook: changes not being saved in database despite hook functioning

It seems like there is a simple issue causing the contact.fullName value not to update, even though contact.middleName updates correctly. The hook is triggering and the changes are showing up in the console logs, but not in the database. The fullName fiel ...

I have implemented a Node.js promise to check if a username exists in the database or not

Can anyone guide me on how to check if a username exists in MongoDB using promises? I'm new to Node.js and would appreciate help in understanding the process. Thanks in advance. var errorsArr = []; var promise = checkUsername(); promise.then(function ...

Obtain the result of two "Synchronous" nested queries using Express and Mongoose

I need to fetch an array of elements structured like this: ApiResponse = [ {_id: 1, name: Mike, transactions: 5}, {_id: 2, name: Jhon, Transactions: 10} ] The user data is retrieved from a query on the "Users" schema, while the tr ...

The issue with Mongoose not saving the modified document persists

Recently delving into Node.js, I embarked on creating a simple blog using Express, MongoDB, and Mongoose to manage post creation, editing, and deletion. While everything is running smoothly, there's an issue with the edit functionality. Below are my r ...

The mongoDB lookup query will display all collections in the database if no matching results are found

I am working with two models named Brand.js and Item.js. The Brand model is linked to the Item model as shown below: Item.js brandId: Number, size: String, description: String, Whenever I execute this aggregation query: let data = await Item.agg ...

Updating multiple documents in Mongoose

I need to make updates to multiple documents in my database with different values. Here is a snapshot of how my current database is structured: [ { "_id": 1, "value": 50 }, { "_id": 2, "value": 100 } ] Unf ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Using two Mongoose collections on a single webpage with Express

There is an issue with my Express route that fetches data from two separate MongoDB collections. One collection displays the results correctly, but the other does not (I have defined schemas for both). router.get('/demo/:cars_getroute', (req, re ...

Restrict users to submitting only one review per journal in Mongoose platform

I am currently working with three schemas: const journalSchema = new mongoose.Schema({ title: String, category: String, subcategory: String, review: [{type: mongoose.Schema.Types.ObjectId, ref: 'Review'}], link: String, description: String, s ...

Using NestJS to populate data will only populate the first element

I have a Mongoose schema in NestJS structured like this: ... @Prop() casinoAmount: number; @Prop() gameHyperLink: string; @Prop() casinoHyperLink: string; @Prop({ type: Types.ObjectId, ref: 'Game' }) games: Game[]; } I'm trying to create ...

Unable to retrieve MongoDB attributes or methods

I'm attempting to access properties or functions within mongoose.connection in order to retrieve the DeleteMany and DropCollection methods, but I seem to be unable to do so. I am initiating the express.js server inside the mongoose connection. mongoos ...

What is the best way to update only a portion of a nested schema in mongoose?

UPDATE: Through numerous trials, I finally discovered a successful method that converts any object into a format that mongoose can interpret. Take a look at the solution provided here: const updateNestedObjectParser = (nestedUpdateObject) => { cons ...

Importing a model file as a schema in mongoose/mongoDB

I came across this helpful model at : 'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var TaskSchema = new Schema({ name: { type: String, required: 'Kindly enter the name of the task' }, Created_date: { ...