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.

Modifying the retrieval or storage object in mongodb

Here is the schema for my account: const account = new mongoose.Schema({ name: String, age: Number, coins: Number, phone: Number, sex: { type: String, default: 'f' } }, { timestamps: { createdAt: ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

Issue with date comparison capability within Aggregate feature while utilizing mongoDB and PHP

I've successfully created a query with date comparison in mongoDB, but when I try to convert that query into a PHP array and execute it using the aggregate method, I'm not getting any data back. Here is the mongoDB Query converted into PHP: $da ...

A comprehensive guide on extracting matching date from MongoDB with Mongoose

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

Updating user information in MongoDB

I'm encountering an issue while attempting to update a user, and it's showing me this error: https://i.stack.imgur.com/sYDv2.png Despite my best efforts, I haven't been able to find a solution. I've tried using different methods from the UserSchema, such ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

What are the best practices for integrating Quill with Node.js and MongoDB?

I'm in the process of creating my own blog, and I really want to have a user-friendly interface for updating the content instead of manually editing HTML files each time. My plan is to use the Quill editor to create blog posts (which are saved as del ...

Error: Latitude and longitude of boundary points

Trying to extract points within a polygon using the query below: loc: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [ [ [ -117.83736, 33.73838 ...

Can you explain how the tagging feature works in the comment section of platforms like Facebook or Azure, where users can mention others by using the '@' symbol?

I am currently working on creating a comment box application similar to Facebook using the MERN stack. While adding simple comments is not difficult, I am curious about how the tagging mechanism works when mentioning a user with an '@' symbol. Sh ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX, lng ...

Set a custom primary key for myself and enforce the exclusion of the default _id field in MongoDB

I have a couple of queries: 1- I need to retrieve data from the database using an ID, but the operation is based on the automatically generated key by MongoDB (e.g. _id). Instead, I want to search based on a field that I created myself like id. To achieve ...

Trapped in a sticky situation with mongoose onsave

Within my MongoDB project, the user schema is structured as follows: var mongoose = require('mongoose'); var Schema = mongoose.Schema; const router = express.Router(); var userSchema = new Schema({ fName: String, mName: String, ...

creating a custom mongoose model using aggregation and filtering

My Review model includes two fields, product and rating. I want to calculate the total rating for a specific product and then find the average by dividing that total by 5. const mongoose = require('mongoose'); const ReviewSchema = mongoose.Schema({ pro ...

What steps can be taken to verify if the userID retrieved from req.user in Passport JS matches the userID in MongoDB before making any updates or deletions

Currently, I am developing a voting application that includes a feature for authenticated users to delete and edit their own polls using Passport JS authentication. My Passport setup with Node/Express looks like this: passport.use(new FacebookStrategy({ ...

Guide on sending an http request using Atlas Trigger in a NodeJS environment

I am working with a simple MongoDB Atlas trigger in NodeJS: exports = function(changeEvent) { // Implementing an HTTP request }; The main objective is to invoke an AWS lambda function from this trigger. Therefore, I am seeking guidance on the synta ...

Locate a subdocument by its unique identifier using the value in the main document

Suppose I have a document with the following structure: { selectedId: ObjectId("57b5fb2d7b41dde99009bc75"), children: [ {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 10}, {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 20}, ...

Using mongo $pull does not eliminate a string from the database

I believe there is a mistake in my syntax, could you help me with removing an item from an array? This is the code snippet: BaseUser.findOneAndDelete({ baseId: req.body.baseId, userId: { $eq: req.body.username } }) .then(user => { console.log ...

Unable to retrieve any results from MongoDB when using the $in operator, experiencing unexpected behavior

Apologies for the not-so-great title, having trouble summarizing the issue accurately. In my Schema, I have defined the language field as an array of strings: 'language': [String] When sending a GET request in the router: let page = Math.max(0, req.quer ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

In order to view the updates in REACTJS, I need to reload the page

Currently, I am engaged in a basic project where I receive user input and store it in a database. Here is the code snippet: const [dataFromDB, setDataFromDB] = useState(null); const fetchDataFromDB = async () => { try { const response = aw ...

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

Error: The users is not mappable in React.js due to an unrecognized function TypeError

I've been struggling with a problem for some time now and I just can't seem to figure it out. If anyone could take a look and help fix the error, I would greatly appreciate it. Feel free to ask if you have any questions. Userdata.js In the userdata.js f ...

What is the best way to retrieve specific information from a group of data using Mongoose?

I need assistance with extracting the number from a collection that contains only a name and a number. I also want to either change the number or store it in a variable. How can I achieve this? let dataSchema = new mongoose.Schema({ name: String ...

Tips for efficiently inserting 10,000 records into MongoDB with identical keys and values

I am currently focused on developing the server side functionality for a new game application. This game will feature a spin wheel concept, and in order to implement this, I need to store a large amount of records. Specifically, I will need to store 10,00 ...

Do the variables declared in app.js have scope access to the functions within routes, in the context of Express and node.js?

While working with express js, I came across an interesting situation. In my app.js file, I had declared the following: var mongoose = require ('mongoose'); var db = mongoose.connect('mongodb://localhost/testdb'); Next, in my /models/userSchema.js f ...

The ID provided does not match the format of a Function Type

Click here for the image import {MongoClient, ObjectId} from "mongodb"; async function handler(req, res){ if(req.method === "POST"){ const data = req.body; const client = await MongoClient.connect("mongoDB URL&q ...

Currently experiencing difficulties with aggregation lookup. Seeking the output of the lookup to match the specified structure

Database Schema categories: [{ category: { type: Schema.Types.ObjectId, ref: 'Category' }, subCategory: [{ type: Schema.Types.ObjectId, ref: 'Category' }] }] Data Retrieval Query { $lookup: { ...

Trouble with Mongoose: New document not being saved in array

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

Retrieving variables using closures in Node.js

I have been developing thesis software that involves retrieving variables within closures. Below is the code snippet written in node.js: var kepala = express.basicAuth(authentikasi); // authentication for login function authentikasi(user, pass, callback ...

What is the best way to authenticate an admin in the front-end using backend technologies like Node.js, Angular, and MongoDB?

Within the user model, there is a property named isAdmin with a default value of false. In MongoDB, I have manually created an admin account with the isAdmin property set to true. When logging in as an admin, the program verifies this and displays "admin ...

Efficiently inserting batches in MongoDB using NodeJs

Currently, I am working with MongoDB version 2.6.9 and NodeJs version 0.10.37. In a previous inquiry related to calculating score from existing fields in MongoDB, I received detailed guidance from chridam. Here is the structured solution provided: var bul ...

A step-by-step guide on printing out longitudes and latitudes stored in MongoDB using Mongoose with console.log()

I'm looking to retrieve latitude and longitude from this source. ** router.get("/", function(req, res) { Map.find({}, function(err, doc) { if (err) { res.send(500, { error: err }); } res.send(doc); doc.map((item ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

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

What is the process for updating multiple documents at once in MongoDB using

I have a situation where I need to update the document in MongoDB for three different chatrooms only if the user's id matches with the member's user_id. However, I am facing an issue where the token is being updated across all devices of the memb ...

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

Retrieve data from a MongoDB collection based on a specific index field

I am looking to extract only the "thetext" field from a specific index in my database when the value of "comment_count" is 1. This is the query I have tried: db.getCollection('mongotesi').find({},{'bug.long_desc.1.thetext':'1'}) In addition to that, I w ...

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

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

Encountering Issues with File Uploads in Express.js with Multer

Currently, I am immersing myself in Node.js through the guidance of a book titled "Web Development with Nodejs and MongoDB." However, I have hit a roadblock when attempting to upload an image using Multer. The code snippet causing me trouble is as follows: ...

Retrieving data from various schemas using Node.js

I am managing two schemas, one for employees (parent) and the other for assessments (child). Each assessment is linked to an employee ID with a pass percentage. Here are some sample data: employees : [ { "_id": 12345, "name": "David", "eval ...

Node error connecting to Mongo database

Having trouble connecting my node server to MongoDB, here is the code snippet I am using: var http = require("http"); var url = require("url"); var Router = require('node-simple-router'); var router = Router(); var qs = require('querystring ...

What is the method for querying a specific field in mongoDB with querymen?

Hello, I am currently in the process of developing a REST API using a generator that I found. If you are interested, you can find more information about the generator here. However, I must admit that I am fairly new to working with the MEAN stack environ ...

Guide on using $lookup with aggregation in Mongoose when dealing with a foreign key within a nested subarray

I am attempting to join three tables in my express-mongo project. One of the tables is named Product and looks like this: Product: _id:5f92a8dfad47ce1b66d4473b name:"Freno 1" createdFrom:5f648f7d642ed7082f5ff91f category:5f92a00c4637a61a397320a1 descripti ...

A promise is given when a value triggers a function

Having a problem with my code in the second function. When I log inside the function, it works fine. But when I assign a variable and call the function, it returns a pending promise instead of true or false. const mongoose = require('mongoose') c ...

Setting up a reference for _id in Mongoose during an update operation

My unique model is presented here. const mongoose = require('mongoose'); const schema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, brandName: { type: String, required: true }, user: { ...

Mongoose - embedded documents are stored as text data

Within my node application, I have a designation model that utilizes the following Schema: var DesignationSchema = new Schema({ _id : ObjectId, designation : String }); This DesignationSchema is then embedded within the users Schema. var UserSch ...

Receiving real-time information from Mongoose - "Cannot modify header information after it has been sent"

I am currently working on an application that utilizes Node, Express, Angular, and Mongoose. To retrieve a large dataset from MongoDB, I am attempting to stream the data. However, I encounter an issue after loading the initial chunk of data where I receive ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

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

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

Exploring the concept of a many-to-many relationship in mongoose.js

Can you please review the schema for Student and Subject below: var Schema = mongoose.Schema var studentSchema = Schema({ name: String, roll: Number, subject: [{ type: Schema.Types.ObjectId, ref: 'subject' }] }) ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Connecting two sets of data from a mongoDB database using vue.js

Hey there, I'm a newcomer to vue and mongodb. I've set up two collections - one for storing user details and the other for business details. When a business registers through a form, their information is saved in mongodb. Now, I've created a form for users ...

Error encountered while populating mongodb database with nodejs

Currently working on a nodejs, express, mongoose project and attempting to seed the database. MongoDB is activated but when I try to run the following command: $ node product-seeder.js (node:2810) UnhandledPromiseRejectionWarning: Error: Invalid schema, ...

Interface circular dependency is a phenomenon where two or more interfaces

In my MongoDB setup, I have created an interface that defines a schema using mongoose as an ODM. import mongoose, { model, Schema, Model, Document } from "mongoose"; import { IUser } from "./user"; import { IPost } from "./posts&q ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

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

Improved method for transferring Mongodb query information to Pug

I'm seeking a more efficient method of passing data to my index.js file in a web development application. With only about a month of experience in web development, I acknowledge that this challenge likely stems from my lack of expertise. Here is the workfl ...

Unable to store acquired data into a list upon retrieval with Mongoose

I am utilizing express.js and mongoose to retrieve data from a collection, store it in a list, and then send it to an ejs file. However, I'm facing an issue where the data is not being stored in the list. Here's my code: app.get("/", (req, res) => { ...

Unity of MEAN Assemblage

My current project involves working with the MEAN stack, particularly using MEAN.js. Although the documentation provides a good explanation of everything, I am facing a challenge when it comes to associating one entity or Model with another. To give an ex ...

Exploring the combination of MongoDB and NextJS: Easily identify corresponding data regardless of capitalization

This code aims to retrieve and display the latest data on Covid-19 related fatalities, recoveries, and critical cases worldwide. The search function is defined as: const search = (e) => { e.preventDefault() //to prevent page reload cons ...

Issue: Trying to render objects as React children is invalid (object found with keys {_id}). If you intended to display multiple children, use an array instead

My intention in the NextJS application is to retrieve JSON data from my MongoDB database using getInitialProps as shown below: static async getInitialProps(ctx) { const res = await fetch('http://localhost:3000/api/endpoint'); const j ...

Node.js and MongoDB query does not return any results

I'm facing an issue with retrieving data from MongoDB using the find() method. Even though there is data in the collection, I'm getting no results. I'm unable to identify the cause of this problem, can someone assist me? Here's the expected result: { err ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

Guide to building a MongoDB database object in conjunction with Next.js

I recently set up MongoDB in my Next.js application using a tutorial I found here: https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb. Within a file called mongodb-config.js, the configuration looks like this: import { MongoClient } ...

`MongoDB impatient for query outcome`

Upon trying to pass the 'db' from my server.js file, where I establish a connection with MongoClient, to routes/api.js for post requests, I encountered an issue. The error message I consistently receive is: TypeError: Cannot read property &apo ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Using Rxjs for MongoDB Document References: A Step-by-Step Guide

Currently, I am working on an app using Ionic2/rc0. In my singleton service, I have a ReplaySubject that maintains the consistency of the current user throughout the entire application. Everything is functioning properly, and I can easily subscribe to it a ...

The predicament encountered with user registration in the realm of Node.js

I am encountering a problem with the sign-up route in node.js and MongoDB. Whenever I attempt to post data using Insomnia, it displays an error message. You can find the screenshot of the error [here](https://i.stack.imgur.com/qnGAv.png). Here is the code ...

Retrieving data from MongoDB for rendering on an HTML page

I have successfully inserted data into my MongoDB database, but I am facing issues with the "get" function to display this data on my HTML page. My current setup involves using Node.js with Express framework and Angular for front-end development and routi ...

What steps can you take to prevent a potential crash from occurring when an unauthorized user attempts to access a page without logging in?

I've encountered an issue where the app crashes when trying to access a page that requires logging in. The reason for this crash is because the page attempts to load undefined data, resulting in the error: TypeError: Cannot read property 'firstN ...

Uploading an image to MongoDB using Mongoose

Hello everyone, I am just getting started with the MEAN stack and I'm looking to add a file upload feature to my project that will store uploaded files in a MongoDB database. Since my images are small, I don't think I need to use gridFS from MongoDB. Can a ...

Occasionally, the 'req.user' property in Passport may unexpectedly become undefined

Currently, I am utilizing Passport for authorization and storing sessions in MongoDB using the 'connect-mongo-session' module. One issue I have encountered is that sometimes, when attempting to log in after some time has passed, the req.user object becomes ...