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.

Unable to retrieve geographical coordinates for the specified location

I'm currently working on saving location data in a MongoDB database. I have created a schema with a field called lastLocation: { type: [Number, Number], index: '2dsphere' }, When I try to input values using Postman, all fields get saved except for the l ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

dealing with the same express routes

I'm currently in the process of developing an application using NodeJS/Express/Mongoose. One of the challenges I'm facing is defining routes for suspending a user without causing any duplication. At the moment, I have routes set up for creating ...

Simulating NestJS Injected Connection Imported from Another Module

Today, I've been facing this persistent error: Encountering an issue with the ClubsService where Nest is unable to resolve dependencies (specifically DatabaseConnection). The error message prompts me to ensure that the argument DatabaseConnection at i ...

bypassing files in mongodb for paging purposes

I need to retrieve specific documents based on the page count parameter in my GET request. For instance, when I send a GET request to http://localhost:3001/posts?page=2, I want to receive 10 documents per page starting from document 10 to 20. router/posts ...

Issue with TypeScript Functions and Virtual Mongoose Schema in Next.js version 13.5

I originally created a Model called user.js with the following code: import mongoose from "mongoose"; import crypto from "crypto"; const { ObjectId } = mongoose.Schema; const userSchema = new mongoose.Schema( { //Basic Data ...

Express error handler failed to catch the validation error

I have a field type in my mongoose schema that is required. I've implemented a custom error handler in express like this: const notFound = (req, res, next) => { const error = new Error(`Not found-${req.originalUrl}`); res.status(404); next(er ...

Back up and populate your Node.js data

Below is the Course Schema I am working with: const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, current_education: { type: String, required: true }, course_name: { ...

Manipulating Arrays in Mongoose by Removing an Object and Updating the Others

As a newcomer in the field of web development, I am attempting to create a basic editable image gallery. In order to achieve this, I have established a Collections schema alongside a Paintings schema: var collectionSchema = new mongoose.Schema({ name: ...

What could be causing the user object's property in mongoose to appear as undefined?

This is my User Schema: var UserSchema = new Schema ({ username: String, password: String, nativeLanguage: { type: String, default: "English" }, The following route fetches a user object and prints it to the console. ro ...

Is MongoDB's find() method returning incorrect objects?

My current task involves running a Mongo query on the Order database to retrieve orders associated with a specific user by using their email. This process is achieved through an API, but I'm encountering difficulties as the returned object contains un ...

Locate and retrieve all the records that contain an asterisk symbol in MongoDB

Could someone provide assistance with finding documents in MongoDB that contain the '*' character using regex? For example, the following regex (db.collection.find{value: new Regex('*')}) should retrieve all documents with '*&apos ...

What is the best method to obtain the combined total of values within a mongoose subdocuments array while querying the parent object?

I am in the process of developing a more advanced hello world application using express and mongoose. Let's assume I have the following Schemas: const pollOptionsSchema = new Schema({ name: String, votes: { type: Number, default: 0 } }); co ...

Make sure that the Mongoose save operation is finished before executing the callback function

Encountering a challenge in my initial node app development, where the callback function is triggered before the database write operation is fully completed. The issue arises when an authenticated user visits site.com/model URL. The system checks the data ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

How can I navigate through embedded MongoDB documents in Node.js to retrieve the values of their keys?

I'm facing an issue with multiple MongoDB documents related to each other. I need help accessing keys and values from the parent document down to the grandchild relational document. Here's the structure I have: const itemSchema = new mongoose.Schema({ ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wondering if I ca ...

Looking to include an additional field in mongoose documents when generating a JSON object in a Node.js application?

var commentSchema = new Schema({ text: String, actions:[{actionid:String, actiondata:String}], author: String }) When retrieving the records, I require a count for action = 1. The desired outcome is to include this count as an additional key ...

The node.js API request is experiencing a unresponsive state

As a newcomer to the world of JavaScript, I am currently learning the basics of Node.js. One task I'm working on involves retrieving a contact from my mongoDB and creating a GET method to return it. Sounds simple, right? Below is the router method I ...

The cPanel Node.js application is experiencing difficulties connecting to the MongoDB Atlas cluster, yet it functions without any issues on

Having developed a website using Node.js with MongoDB Atlas as the database, I encountered no issues while testing it on Heroku. However, after purchasing my domain and switching to proper hosting, I faced challenges. I attempted to set up my website by c ...

Updating with `mongoose.findOneAndUpdate()` alters the existing data stored within my Node.js application

I came across another person seeking advice on a value override, but unfortunately it remains unanswered. Hopefully, someone can point out the mistake I might be making! Here's the situation... var vote = req.body.vote; var boolVote; (vote === 'good') ? ...

The IF statement following the FOR loop gets evaluated prior to the execution of the mongoose query

I am facing an issue with the asynchronous nature of nodejs. I need the IF statement to wait until the FOR loop, which includes a mongoose query, is completed. Can someone help me make this code synchronous so that the FOR loop finishes executing before mo ...

Challenges with Comparing Dates in MongoDB

I am currently using Mongoose to retrieve data based on a specific date from my database. Specifically, I am trying to fetch any account that has not been accessed for more than an hour. However, when executing the query below, I am not receiving any resu ...

"Encountering socket issues while making a post request with Express, Mongoose

I'm encountering an issue where my post request using Postman to localhost:5000/api/auth/register keeps getting hung up on the socket. Can anyone offer some insight into what might be causing this problem? Thank you in advance! (I am utilizing MongoDB's fr ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

Unexpected null value returned upon form submission with Mongoose and ExpressJS

I am encountering an issue with sending data from a basic HTML form to MongoDB using Express. When I try to post it, I am getting null as the result. The Schema I used is: commentname: String. Below is the snippet of the HTML code: <form id="form ...

What is the best way to modify an array of ObjectIds within a MongoDB (Mongoose) collection?

I'm trying to figure out how to update an array of indexes in my code for a final result. I am using mongoose to build my Schema. Here is my Schema: var postSchema = new Schema({ title: {type:String}, content: {type:String}, user:{type: ...

The response for object notation of a nested JSON object is not defined

Can anyone provide assistance, please? I have a JSON object example that I store in my mongoDB through mongoose: {"@context":"https://w3id.org/chainpoint/v2", "type":"ChainpointSHA256v2", "targetHash":"5eaad1259897efd03dc8ea30d1a0d717fec7ec23b6b1487ad689 ...

Array of Objects Returned by Mongoose

Need help understanding an issue. I'm facing a problem where my API is returning the whole object as an array for one route, even though the schema is identical to another route that returns the object correctly. The only difference I can see is that one ...

Unable to generate an index with mongoose

I'm currently working on developing a search functionality within my Node.js application that utilizes Mongoose, aiming to create a full-text search index in Mongo: postSchema = mongoose.Schema({ xx : String ....... }).index({ ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error explanation and thr ...

I am looking to manage user-related data in the comment model using mongoose and express

I have a user, post, and comment modal This is my comment modal import mongoose from "mongoose"; const CommentSchema = new mongoose.Schema({ postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", }, userId: { t ...

What is preventing me from being able to retrieve the properties of this object in JavaScript?

Recently, I started working on a side project as a way to practice what I learned from a web development course on Udemy. However, I encountered an issue with a middleware function that I wrote. This is the function causing trouble: const User = require(& ...

The benefits of using express-session-mongo compared to creating your own solution

Being new to nodejs/mongo, I decided to create my own session middleware instead of using the express-session-mongo plugin. In my custom middleware, I save the user's id in the session (via express's session middleware) and retrieve the logged-i ...

Utilizing Node.JS and Typescript to correctly define database configuration using module.exports

I am currently utilizing Mongoose in my node.js application, which is written in Typescript. The Mongoose documentation provides clear instructions on how to connect to their database like this, but I prefer to have the configuration stored in a separate ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Error: Callback function in Mongoose Populate is returning undefined

I have a query set up in MongoDB where I am trying to display all subcollections of the schema while excluding the account ID. The issue is that I am getting "undefined" as the result for the callback "list_data". Here is how my query looks in my routes: ...

What is the reason behind the catch() block within a mongoose query not causing the function to exit when we return next(err

Calling this simple function from my express router is causing unexpected behavior. export const createThing = async(req,res,next) => { const {body} = req; const thing = await Thing.create(body).catch(err=>next(err)); console.log(&ap ...

Retrieve a specific item from mongoDB by using Mongoose and express.js, and display a customized page if the item is null

I have been attempting to retrieve an object from a mongodb database using Express. When the object exists, I am able to successfully fetch it. However, when the object does not exist, I want to implement some sort of custom message or page display instead ...

What is the best way to put this model into practice?

Is there a way to successfully implement the following structure? [{ "title": "pranam", "year": "2016", "rating": 9, "actors": [ { "name": "Amir", "birthday": "16 Aug 1982", "country": "Banglades ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

Retrieve the updated value following an updateOne() operation

Is it feasible to retrieve all updated values or values with a difference after calling updateOne()? _.each(gameResult, function(gameResult){ bulk.find({"user" : gameResult.user, "section" : gameResult.section , "code" : gameResult.code}).upsert().up ...

Waiting for a Node.js/JavaScript module to finish running before proceeding

I've developed an express.js application that integrates with MongoDB using mongoose. Currently, I have the mongoose connection code stored in a separate file since it's used across multiple modules frequently. Below is the connector code: con ...

Is there a way to assign the versionKey __v to a custom field during mapping?

I am currently working with the following schema design: const articleSchema = new Schema<IArticle>({ title: { type: String, required: true, }, overview: { type: String, required: true, }, }); In order to compare the current ...

Tips for managing data received from an Axios post request

I have a setup with a react frontend and node.js backend. Currently, I am successfully sending a POST request using axios: const [logins, setLogins] = useState({}); function updateLogins(e) { setLogins({...logins, [e.target.name]:e.target.value} ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

Utilizing Mongoose for incorporating embedded documents within forms

Within my Mongoose schema named Question, I have a straightforward setup for storing questions and their corresponding answers. Answers are defined in a separate schema and stored as embedded documents within the Questions collection. Below is the outline ...

The Node server experiences a crash due to a MongoDB duplicate key error 11000

Encountering a duplicate key error (E11000) is expected, but it should not crash the server. The error occurs due to a unique index on the email field. This is the controller method: exports.saveOAuthUserProfile = function(req, profile, done) { Use ...

Exploring the power of dynamic routes in node.js to locate individuals within my mongoose database

app.get('/admin/reservas/:param', function(req, res) { var param = req.param("param"); console.log(param); mongoose.model('Something').findOne( { id: param }, function(err, obj) { ...

Executing both push and pull operations simultaneously using mongoose and Express in MongoDB

Currently, I find myself in a scenario where I need to simultaneously push and pull data. I've designed Schemas for categories and posts, where each post can be associated with multiple categories. This is achieved by using Object Referencing method ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); $scope.loadsCards( ...

Generate a set of random filtered results using mongoose in a Node.js environment

In my attempt to create a simple app for generating random exams, I have defined the following schemas: Question schema: var questionSchema = mongoose.Schema({ text: String, type: { type: String, enum: ['multichoice', 'numerica ...

Assigned a gender to my _id using the first name and last name

Hello, I am attempting to generate an _id in mongodb using a combination of the first name and last name. However, I'm encountering a problem with this process. My desired format for the id is like this: '_id':'midoxnavas' where 'midox' represents the firs ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...

Encountered a problem with Node and Mongoose: "TypeError: Object.keys called on non-object" error when trying to save

Within the user schema below, there exists a foobar.events field. I am attempting to add new hashes (received from an API POST request) to this field. var userSchema = mongoose.Schema({ foobar: { id : String, token : ...

What improvements can be made in the MongoDB structure for a more efficient package or wallet system?

I am currently developing a package/wallet system that involves multiple users. Within my mongodb database, I have organized the data into 4 collections: Business const businessSchema = new mongoose.Schema({ name: { type: String, unique: true }, . ...

Establishing a Fresh User with npm Commands

I'm having trouble creating a user with a js file in my package.json scripts. I've set up the script to run with npm run create_admin, but for some reason, the user is not being created and no errors are showing up. After some initial debugging, it seems l ...

The error message "NodeJS TypeError: Model is not a constructor" indicates that

I am facing an issue with my Angular5 app making requests to my NodeJS Api. Specifically, when I try to make a put request, it works the first time but throws an error on the second attempt saying that my Model is not a constructor. In my NodeJS backend, I ...

Middleware for cascading in Mongoose, spanning across various levels in the

I have been working on implementing cascading 'remove' middleware with mongoose for a project. In my database structure, I have nested collections as follows: 'modules' -> 'modulesInst' -> 'assignments' -> 'studentAssignments' When a module is d ...

Mongoose: utils.populate function encountered an error with an invalid path. The expected input type is a string, but instead received a value of

Although I am not a complete novice with Populate user, I seem to be facing some issues now. My current dilemma involves populating my designerId, which is of type ObjectId. Please review the code snippet from my route below: ordersAdminRouter.route('/cu ...

Exploring Mongoose: A Guide to Populating Data from a Parent to a Child

I'm currently diving into the world of mongoose, where I have set up 3 collections (User, Post, Comment), each with its own unique schema: User { fullName: String, email: String, } Post { author: {type: mongoose.Schema.Types.ObjectId, required: tru ...

Mongoose TypeScript Aggregation error: is not a valid property of type 'any[]'

Attempting to replace a standard mongo call with an aggregate call. The original code that was functional is as follows: const account = await userModel .findOne({ 'shared.username': username }) .exec(); console.log(account._id) The n ...

What is the cause behind the mongoose populate function delivering an irregular array and how can it be resolved?

I'm currently using mongoose's populate function to retrieve and populate a list of data like this: Account.findOne({_id:accountId}).populate({ path:"orders.order", match:{_id:orderId}, selecte:'', options: ...

What is preventing this POST request from successfully resolving and returning a 200 status code, despite the fact that the database is being updated?

I am a beginner in web development and facing an issue with writing a post request in Express using MongoDB as the database. The problem is that even though the document is created in the database, it does not return a 200 status code. Below is the functi ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

Is a single connection sufficient in Node.js when using the Mongoose driver to handle concurrent requests in MongoDB?

Can a single connection pool size of { poolSize: 1 } be used for multiple simultaneous web service calls in MongoDB? Will the connection be reused or will it result in an exception? I am using the Mongoose driver in Node.js with MongoDB as the database. ...

Mongoose and Mocha detected an absence of listeners; error in validation

Currently, I am in the process of setting up a unit test for the POST function within my express app. The Mongoose schema that I have in place is quite simple, consisting of two fields, with one being marked as required. During testing with mocha, when I ...

What strategies can be implemented to enhance the create and update performance for a high volume of entries in Mongoose/MongoDB?

I am seeking the most efficient method to bulk create/update in my Express application that utilizes Mongoose/MongoDB. Is there a way to achieve this with a single database operation? On the frontend, users upload a CSV file which is then converted into a ...

What is the necessity of verifying that the password remains unchanged once the JWT has been generated?

I'm having trouble understanding why it's necessary to check if the password has been changed after issuing the JWT. I have a code snippet here that handles user authorization, but the reason for this specific check is unclear to me. Can someone explain wh ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then().err ...

Tips for exploring the array populated with references in Mongoose

Hello, I am delving into MEAN stack development for the first time. Can anyone guide me on how to perform a search in Mongoose populate array? The array contains a reference. Discussion Schema: const discussionSchema = new Schema({ user_id: { type: ...