Questions tagged [mongodb]

MongoDB is an exceptional, highly efficient, open-source NoSQL database that functions with a document-oriented approach. It offers extensive support for numerous programming languages and platforms used in application development. For any queries related to managing servers, you can visit the informative platform at mongodb.

What is the method to determine the number of keys that have the same value in a JavaScript object?

My goal is to achieve functionality similar to this: var data = [ { tag:'A', others:'Abc' }, { tag:'B', others:'Bbc' }, { tag:'A', others:'Acb' } ] I am attempting to group the 'tag' ...

Failed to cast value "some_id" to ObjectId for the field "_id" in the "Category" model

Encountering an issue while using findOne from Mongoose version 5.9.12. The error I received is shown here. I also encountered another error which can be viewed here. Here is my code: [code][2] You can find the screenshot of the error here. Additionally ...

MongoDB Driver Alert: MongoError - Cursor Not Found. Cursor ID 7820213409290816 was not located in the specified namespace db_name.collection_name

Having successfully created a Nodejs API server that connects to AWS MongoDB (version: 3.6), everything seems to function flawlessly when calling one specific API endpoint (api/lowest). However, upon making multiple simultaneous calls to this API (15 in to ...

Encountering connection timeout issues when trying to link MongoDB Atlas with Mongoose

I've been attempting to establish a connection to my MongoDB Atlas database using mongoose, but unfortunately, I keep encountering the following error: (node:2327) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-abjwg.gcp.mongodb.n ...

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 ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what I'm ...

"Combining Node.js, MongoDB, and Vue.js to create a dynamic dependent select dropdown: a step-by-step

Seeking guidance on setting up a dynamic dependent dropdown list using node js, mongoDB and Vue js. As a newcomer to this concept, I'm unsure where to begin. Here is the scenario I am facing: I need assistance in creating 2 dropdown menus for country and ...

Update Mongoose data conditionally using an array of objects

I am facing a challenge with my Cart schema in Mongoose. The CartItems are stored as an array of objects. { _id: string; items: [ { product: string; options: { size: string; color: string; } quantity: number; ...

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 ...

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 ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi/l/email-p ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...

filtering a second list by manipulating the first list's state and triggering a method with the help of checkboxes

Dear moderators, I would like to address an ongoing query that is a continuation of a previous question. You can find the original question here. Although I initially attempted to edit the original question, it became necessary to rewrite most of it, so p ...

New Relic identifies mysterious delays caused by MongoDB's findOne method

After setting up newrelic to pinpoint the bottlenecks in my app, I discovered a major issue that has left me stumped. The source of most delays seems to be mongoDB user.findOne, but the biggest challenge is locating where in the code this delay is occurri ...

What are the most effective strategies for efficiently handling enormous json files?

I have a substantial amount of data stored in JSON format. I am considering the best approach to manage this data, such as loading it into MongoDB or CouchDB on a remote host like Mongolab, using a flat-file JSON database like , parsing the files directl ...

Searching for a string in an array using the $in operator in M

I have a custom model defined as follows: var MessageSchema = new Schema({ msgID: String, patientList: [String], created_at: Date, updated_at: Date }); The patientList is always dynamic in nature. I am attempting to construct a Mongoose ...

Having trouble updating a specific document in my MongoDB collection

I am facing an issue with my function that reads data from the database. I am trying to change the value of the "hasVoted" field in my Voters model from false to true, but it is not reflecting in the database. Even after setting data.hasVoted = true and c ...

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(& ...

Retrieve request header in Nest.js Passport local strategy

Is there a way to retrieve the request headers in passport local strategy? My objective is to establish a separate database for each entity using mongodb, and I need to determine the subdomain before authentication in order to connect to the correct data ...

Issue encountered: Unable to establish successful private messaging functionality with NodeJS Socket.io

I've been having trouble for more than a week now while developing my chat app that allows users to send private messages. Unfortunately, the private message function is not working properly. Let me provide you with the code that I'm using when a user wan ...

establish a connection to a MongoDB database running on a dedicated EC2 instance

I am currently managing two separate instances on AWS, one for a node application and the other for mongoDB. Despite trying to establish a connection to mongoDB from the node application instance, I keep encountering an error reading "504 Gateway timed out ...

Is the $slice feature integrated into the php driver?

Can I use the '$slice' feature with the update() and $push functions in MongoDB? I have already attempted this, both with and without casting to (object). $db->collection->update( array('_id' => new MongoId($id)), (object)array( '$pu ...

Unresolved Issue: Inoperative Mongoose Populate and ExecPopulate

In my application, I have two mongoose models: 'Department' and 'Course'. These models have a one-to-many relationship, with the department ID stored under the 'department' field in the course document. My goal is to query all the departments and populate ...

Next.js is reporting an error where the Schema has not been registered for Mongoose

Recently, I started using next.js and encountered an issue when calling an API with a reference to another document. Mongoose threw an error saying "Schema hasn't been registered for model". Below is the code snippet: Models Task.js // Task Model Code / ...

Error encountered in Express.js blogging app: Issue arises when attempting to filter posts by category, resulting in a "Cast to ObjectId failed" error

Currently, I am developing a blogging application using technologies like Express, EJS, and MongoDB. In the application, I have structured posts into different categories, each stored in its own collection. However, I encountered an issue while attemptin ...

What is the method to output JSON using the mongodb ruby driver?

After executing a find query in the mongodb JavaScript console, I receive a well-formatted JSON response. However, when running the same query using the Ruby driver, it stores the result as a Ruby object. Is there a way to convert this back to JSON forma ...

Chokidar encountered an error in C: ode_modules: EBUSY error - the resource is either busy or locked when trying to perform a lstat operation on 'C:hiberfil.sys' file

Every time I start or restart my backend server, I encounter the following error in my terminal: Error from chokidar (C: ode_modules): Error: EBUSY: resource busy or locked, lstat 'C:hiberfil.sys' Error from chokidar (C: ode_modules): Error: EBUSY: re ...

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({ ...

Having Trouble with Bcrypt Saving Your Password?

Having trouble with saving a new password to the database when hashing it? I am utilizing MongoDB, NodeJS, and Passport for allowing users to change their passwords. UserSchema.pre('save', function(next) { var user = this; var SALT_FACTOR = ...

Having trouble connecting to express-session through socket.io?

I am currently working on a project that utilizes the socket.io and express-session packages. However, I am encountering an issue where I am unable to retrieve the session object that was previously set during login or authentication. Below is the code sn ...

Utilize a MongoDB query to locate a single document and include a conditional statement within the update operation

I've been struggling with this problem for quite some time now and I could really use some guidance from experts here on SO. Essentially, what I am trying to achieve is to locate a specific document using a provided _id, and then execute a conditional stat ...

Ensuring uniformity in simultaneous read actions within MongoDB

I have a Node.js API called /create/appointment that performs two operations: STEP 1: Checking for an active appointment in the database. STEP 2: Creating an appointment if it does not exist. There are three collections: doctors patients appointments ...

Why is my res.render() in Node.js and Express not functioning as expected?

After exploring various resources and conducting extensive research online, I have yet to solve the issue I am facing. My problem lies in attempting to render an ejs template, but nothing seems to be taking effect. Below is my code: Front-end script: $( ...

Issue encountered during installation of mongojs in nodejs is as follows

Encountering an error while attempting to download MongoDB. Any advice you could offer? https://i.stack.imgur.com/UwvgF.png Managed to fix some Python setup errors, but still facing issues with Kerberos. Assistance would be greatly appreciated. https:// ...

Struggling to Display/Retrieve a MongoDB Entry by its Unique Identifier in React

Despite my best efforts and a few minor setbacks, I am still struggling to retrieve an object by its ID in my React frontend. The issue arises when trying to access properties of the object in my Post Component. Even though the data seems available based o ...

Tips for expanding the count and confirming whether the user is a fan using node.js?

I am looking to update the like and dislike count in videoSchema based on the likedislikeSchema. Can you provide guidance on how to achieve this? For example, when a user likes a video, the like count should be incremented in videoSchema, and the videoId ...

Nodejs encountering issues with reading data from collection despite having "readWrite" role in Mongodb permissions

I developed an application using Node.js and MongoDB. In MongoDB, I added a new user with the roles specified below: { "_id" : "testdb.testdbuser", "user" : "testdbuser", "db" : "testdb", "roles" : [ { ...

Exploring the concept of embedding documents in Mongoose through modeling

I have structured two different kinds of events (events and subevents) in a MongoDB database as shown below: var EventSchema = mongoose.Schema({ 'name' : String, 'subEvent' : [ SubeventSchema ] }); var SubeventSchema = mongoose.Schema({ 'name ...

Storing Documents and Distributing them to Customers (Using NodeJS, Express, MongoDB, and Mongoose)

Is there a way to save files in mongoose? For instance, let's say I have a route for the POST method at /, and for the GET method at /. When posting to /, the goal is to save the uploaded file to a MongoDB database using mongoose. Then, when someone t ...

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 ...

Store unique elements in an array using MongoDB without any duplicates

I have a scenario where users can add elements to an array of objects. The issue arises when user 1 tries to add the same book multiple times, while user 2 already has it in their list. In this case, User 1 should not be able to add the book at all. Here i ...

Increasing Nested Values in MongoDB Using NodeJS

Looking at this JSON structure: JSON = { "change_number": "CRQ91320s23", "change_description": "Nexusg work", "date": "2/10/2020", "changeowner" : "Jeff ...

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { con ...

I am unsure about how to properly implement the reduce function

I am struggling with implementing the reduce function in my code. I have data output from a map function that consists of two documents. For example, one document contains: key "_id":"AD" "values" { "numtweets" : 1, "hastags" : ...

Comparing Mongoose and MongoDB in Node.js: Weighing the Benefits of Each

Just starting out with Node.js and noticing the multitude of libraries available to work with MongoDB. The two most popular options appear to be mongoose and mongodb. Can someone provide a comparison of the pros and cons of these extensions? Are there any ...

Unending Mongoose request delay

Situation: Using Mongoose v4.7.6 Working with MongoDB v3.2.11 Currently facing issues regarding database errors in my software. Encountering a problem where mongoose requests hang when the database is disconnected and only resume once reconnected. Th ...

Totally at a standstill. (Problem with MongoDB in my MERN stack)

Currently developing an app, focusing on a feature that takes user input and stores it in the database. Although I've implemented this in past projects, I'm facing a persistent issue. Upon user input submission, the data is sent to the backend where it pr ...

Retrieving data from an array in MongoDB

Currently in my MongoDB database, I have the following collection: { "_id" : ObjectId("5df013b10a88910018267a89"), "StockNo" : "33598", "Description" : "some description", "detections" : [ { "lastDetectedOn" : ISODa ...

Tips for adding two objects within a single update function in MongoDB

Utilizing node.js to interact with a MongoDB collection. Employing objects to organize data efficiently, similar to the method explained here Facing an issue where attempting to push data into two distinct arrays - one for "Temperature" and another for "T ...

Result is not defined after aggregating in MongoDB with Mongoose framework

I am struggling to retrieve comments from a MongoDB collection (using Mongoose) and compute the total number of comments as well as the average rating using the aggregate pipeline. However, if the initial $match query returns no results, the script crashes ...

Retrieve a comprehensive compilation of mongoose errors within a unified response

Currently, my backend development involves using Node.js, Mongoose, and Express.js. I am in the process of creating a list of users with mongoose. [ { "username" : "abc", "password" : "123", "displayname" : "ABC", "emai ...

Utilize the Mongoose framework to incorporate the " _id" field from MongoDB into the projection

I'm working on retrieving a Mongo document using Node.js and Mongoose in the following manner: var app = express(); var Thread = mongoose.model('threads', schema); app.get('/api/closed/all', function(req, res) { Thread.find({ IsCLOSED: true }, functio ...

Working with a variety of operators in MongoDB

Can this code section be improved? 'update': function (req, res) { var item = req.body.item; var tags = []; tag.find(function (err, _tags) { tags = _tags; post.update({ '_id': item._id }, { $set: { Text: item.Text } }, function ...

A variable must be defined within a specific block in order to be recognized

In an effort to enhance my code within a passport function, I am looking to pull values from a mongodb Database rather than from an array. The initial functioning code appeared as follows: passport.use( new LocalStrategy( { usernameField: ...

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 ...

What is the reason behind mongoose's utilization of schema, especially when MongoDB is known for its schema-less nature?

Just diving into the world of mongodb and feeling like a complete newbie. I've been utilizing mongoose to interact with mongodb through node.js, and while everything seems to be functioning properly, I can't help but wonder about the rationale behind it. ...

Encountering an incorrect entry in the Mongo database while attempting to modify an entry

I am currently working on a project using Node.js with Express and MongoDB. The goal is to search for and update an entry (referred to as an "event") in the database based on its unique id. The id is passed in the request body as tempEventInfoForEdit, whic ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

WebStorm unable to resolve function or method mongoose.connect()

After setting up my Node.js application, I encountered an issue while configuring the server.js file. I ensured that I added mongoose to the list of dependencies in the package.json file. However, when trying to connect to MongoDB Atlas by requiring this p ...

Troubleshooting problems with querying in mongoose and express: A comprehensive guide

As someone who is still relatively new to dynamic routing, I am struggling with implementing it correctly. My goal is to create a function that retrieves the user's purchases from the database and exports it as a CSV file. Everything was working fine ...

Run MongoDB from within your application using Node.js

Currently, I am working on developing a component that will be available through NPM. The requirement for the application is to establish a connection with the database. In case the user does not provide the necessary details for the database URI in the co ...

Inputting model variables into a Mongoose schema

One issue I have is with a mongoose model that has an association with a user model. Here's the code snippet: var exampleSchema = mongoose.Schema({ name: String, <some more fields> userId: { type:mongoose.Schema.Types.ObjectId, ref: &a ...

Using the MERN stack in conjunction with Socket for MongoDB provides the ability to display real-time data on the frontend directly

As I work on setting up a website using the MERN stack, my backend will continuously fetch data from APIs and sockets to save it in a MongoDB database. For the frontend React, I aim to display and update this data in real-time using Socket. I have concern ...

Second application fails to trigger collection hook

I have developed an application using Meteor 1.4 and currently running it on port 3000 (referred to as A). Now, I need to utilize the database of A in another application (referred to as B). In the console of B, I set the MONGO_URL as follows: export MONG ...

Tips for accessing the most recent embedded document added using the push() method

I'm having difficulty determining the feasibility of this situation. While using the mongoose blog example to illustrate, my specific use case is a bit more complex: var Comments = new Schema({ title : String , body : String , date ...

Issue encountered when attempting to include new members in the replica set

When attempting to add members to the replica set, an error was encountered with the following message: "exception: need most members up to reconfigure, not ok." Running rs.status() provides the following information: { "set" : "rs0", "d ...

What is the process for accessing data of signed-in users?

I currently have a mobile app developed using the MERN stack that utilizes passportjs for user authentication and login (linked to a mongodb database via axios). However, I am facing an issue where I cannot associate the data/log entered by the user with t ...

What is causing the issue of documents not being removed from the mongoDB database?

I've been trying to delete a document from the MongoDB database, but for some reason it's not working as expected. Even though the console doesn't show any errors and displays the query object correctly, the respective document still remains ...

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 ...

Ways to showcase pictures stored in MongoDB gridFS

I have been working on developing a webApp that allows users to upload images, and in order to accomplish this task I am utilizing gridfs. I have managed to successfully save the images, but I encounter difficulties when it comes to displaying them. In o ...

An error is triggered when using db.listCollections() in an ExpressJS environment

I am currently working with ExpressJs and MongoDB, but I've encountered an issue with the following code: var db = monk(DB_URL); app.use(function (req, res, next) { req.db = db; next(); }); app.get("/view_collections", function (req, res) { var d ...

Unexpected database query result in Node.js

In my newuser.js file for a node.js environment with a mongodb database managed through mongoose, I have the following code: //newuser.js //This code is responsible for creating new user documents in the database and requires a GET parameter along with a ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

Guide on getting a website name from a URL using Javascript

Is there a simple method to extract the site name from a URL string? For example: http://www.mysite.com/mypath/mypage -> www.mysite.com http://mysite.com/mypath/mypage -> mysite.com The JavaScript code runs on the mongodb CLI side, not within ...

Utilizing MongoDB and Express to access collections within a controller

Is there a way to access the collection in the controller using mongodb and express? I came across this code snippet in the mongodb documentation db.getCollection("countries");, but how do you import the database name: db into a controller? serv ...