Issue I am trying to add the ObjectId as a "Foreign key" to a collection. I have the previous id to link but I am having problem with the script. Following is the script db.users.find().forEach(function (user) { var cursor =
Continue readingTag: mongodb
How to select MongoDB indexes for complex queries
Issue Answering this question, probably, involves multiple issues, so it should be fun 🙂 So, I have a collection with fields {a, a1, s, i, j}. field a1 always has the same value as a value of field s is
Continue readingFind All Records Between a Range of Two Numbers in a MongoDB Query
Issue Is there a way in MongoDB to get records between a range of numbers? In my example, I am finding the records that match common: 1, and am using a fake range() function to get only the records between
Continue readingMongo error, i can't run my two applications
Issue I generated two projects with the AngularJS Full-Stack Generator. The problem is when i run the command gulp serve in both projects, only opens one of them. In the console of the other project it show me: (node:1236) DeprecationWarning:
Continue readingI am getting an error "Error: User validation failed" in MongoDB
Issue I am getting an error after trying to use the POST method through postman to register a user. I have created a simple Schema for the register route. Error: Error in register: Error: User validation failed: password: Cast to
Continue readingmongoDB find from one collection and save in another collection
Issue I want to find a user from my user collection then inserting this exact user in another collection that have the same schema. Here is my implementation: (Controller) const user = await User.findOne({ _id: id }); if (user) {
Continue readingFetching data from server in Remix.run
Issue I was exploring Remix.run and making a sample app. I came across an issue that has been bothering me for some time now. Correct me if I am wrong: action() is for handling Form submission, and loader() is for
Continue readingInsert data on already existing User in mongodb
Issue Can anyone help me solve this problem, I’ve been stuck days on it and haven’t found any solution to. I have this user schema in my mongodb / node js: const userSchema = new Schema({ username:{ type: String, required:
Continue readingIs there a way to request something from the backend and contiously search and refresh the database until it finds a match? then send the response
Issue I am struggling to make my own matchmaking in a multiplayer game of two players. I have a button that says "play",and i want if the user presses it to change in database his schema property "inQueue to true"
Continue readingReset password doesn't update my password in mongodb base
Issue I am first time making APIs about forgot password and then reset password. I am facing strange issue. There is not a single error, it gives me success status that password is updated. The problem is that in my
Continue readingMissingSchemaError: Schema hasn't been registered for model "User, userSchema". Use mongoose.model(name, schema)
Issue hope you’re doing well. i’m following a tutorial ( from 2019 ), and i’m facing this error at the moment. here’s the code. ( let me know if you need anything else ) // index.js // const express =
Continue readingDiscord Bot | Ranking (Leaderboard?) System with discord.js and MongoDB
Issue I have a few questions to ask about a ranking (leaderboard…?) system in discord.js using MongoDB. I am following a tutorial made by CodeLyon for the setup of MongoDB, but afterwards I went ahead and created my own XP
Continue readingBufferizing data from stream in nodeJS for perfoming bulk insert
Issue How to bufferize efficiently in nodeJS on events from a stream to bulk insert instead of unique insert per record received from the stream. Here’s pseudo code I’ve got in mind: // Open MongoDB connection mystream.on(‘data’, (record) => {
Continue readingreferenceerror: cannot access 'user' before initialization
Issue error showing: referenceerror: cannot access ‘user’ before initialization , I encored the password, after I called use, or there is an error will come like ***hashedPassword is not defiend *** so this why I call after bcrypt but that
Continue readingHow can I async await multiple synchronous MongoDB findOne functions with NodeJS
Issue I am using "await" on multiple MongoDB ".findOne" functions to different collections one at a time. I would like to let them all run synchronously together and somehow know when they are all ready to use. Instead of doing
Continue readingMongoose Model Custom Error Message for Enums
Issue I would like to customize the validation messages that my Mongoose Models produce. I tend to NOT put my validations (e.g. required) on the schema object directly because there is no freedom to have custom error messages. e.g. sourceAccountId:
Continue readingHow to create interconnected schemas in MongoDB with Mongoose?
Issue I am creating an web app for users to store their daily expenses. The app is in NodeJS and using Express. The schema for collecting users and users’ data is as follows: const dataSchema = new mongoose.Schema({ email:String, date:String,
Continue readingMongoose: Find name similar to input
Issue I have an auto complete input box that I am working on and I am trying to make a mongoose endpoint that will get me user objects based on data from the input. The data can be incomplete, but
Continue readingUnable to fill mongodb document with external api data
Issue I am trying to fill my mongodb document with data from unsplash and randomuser api. const userdata = await axios.get("https://randomuser.me/api/?results=51"); const imagedat = await axios.get( "https://api.unsplash.com/photos/random/?count=51&client_id=GWDzPpjHk743C2QnVBRxu8PtmOI3npF5sePZZ7o0pg4" ); I call both apis for 51 results but after 22 results the
Continue readingInstalling and Running MongoDB on OSX
Issue If someone can provide some insights here I would GREATLY appreciate it. I am new to MongoDB, and (relatively) new to the command line. I had a express/node.js app running on MongoDB locally successfully, but upon restarting my computer,
Continue readingHow to do custom repository using TypeORM (MongoDB) in NestJS?
Issue I have a question. With @EntityRepository decorator being marked as deprecated in typeorm@^0.3.6, what is now the recommended or TypeScript-friendly way to create a custom repository for an entity in NestJS? A custom repository before would look like this:
Continue readingGroup documents in two by array field Mongo Aggregation
Issue How do I group the date field one to the next one in each document? { _id: ObjectId(‘…’), date: [ISODate(‘2022-05-27T00:00:00.000+00:00’), ISODate(‘2022-05-28T00:00:00.000+00:00’) …] } The desired document would like this: { _id: ObjectId(‘…’), date1: ISODate(‘2022-05-27T00:00:00.000+00:00’), date2: ISODate(‘2022-05-28T00:00:00.000+00:00′) } Solution Here’s
Continue readingMongoose where value in array
Issue I have the below code to return all blogs where the blog author ID is equal to the ID of the first administrator (orgAdmin) in an array: let officialBlogs = await Blog.find().where(‘author.id’).equals(help.orgAdmins[0]); But I can’t work out how to
Continue readingQuering documents into one specific property in MongoDB
Issue I wanted to query all "doc" properties inside the "doc", like a nested. I guess you can understand further what I want to explain from the code below: mongoose.connect("mongodb://127.0.0.1:27017/stationDB"); const docSchema = mongoose.Schema({ naturka: String, address: String, coefficient: String,
Continue readingusing ObjectId as a data type
Issue I’m trying to create a schema for an object and I’m using ObjectId as type but he gives me an error const mongoose = require("mongoose"); const permissionsSchema = new mongoose.Schema({ roleId: { type: ObjectId, required: true, }, menuPageId: {
Continue readingAxios request works only on second request
Issue I am building a user login system and currently the way I have it set up, the user types in their email and password and then that information is sent to my server to be checked if accurate. If
Continue readingJSON empty when is called from another file
Issue I’m learning NodeJS and MongoDB. I dont know what is happening with this function. getAllUsers = async () = { let user; let result = await new Connection().connect(); if (result.status == "ok") { user = await User.find(); } return
Continue readingExpress and Mongoose: Cannot read property 'name' of undefined in Postman
Issue I am attempting to create and insert ‘user’ json documents, defined in the model below, upon a POST request to localhost:3000/api/student. I am greeted with the following error using postman to send POST requests: TypeError: Cannot read property ‘name’
Continue readingHow to export a Mongoose model from a CommonJS module in TypeScript NodeJS app
Issue I have a model defined in models/user.ts import mongoose = require(‘mongoose’); var userSchema = new mongoose.Schema({ … }); var User : mongoose.Model<any> = mongoose.model(“User”, userSchema); Normally in JavaScript, in order to use the model User in a NodeJS app
Continue readingReferenceError: err is not defined when connecting mongodb with nodejs express
Issue I was following an ecommerce website tutorial on Nodejs express (handlebars template). When try to connect to mongo dB (installed on system i.e., port 27017) it shows if(err) console.log ("connection Error"+ err) ^ ReferenceError: err is not defined var
Continue readingHow can I restrict the ability to post and save data to the database to only the admin in node.js?
Issue In the users table, I have two collections, one of which is admin and the other which is not. Now I only want admin user to post data. Here is the post request: router.post("/bus/add", auth, async (req, res) =>
Continue readingHow can I query my database and return all user documents?
Issue I’m trying to test an API that returns all user documents in Mongo DB, however it keeps returning an empty result. I can’t seem to figure out where my code is going wrong. here’s my user model const mongoose
Continue readingMongoDB showing the schema as undefined
Issue While retrieving documents from database values are shown as undefined in console log. Piece of code that causing that issue. const stockSchema = mongoose.Schema({ rollingStockNumber: String, docs: { naturka: String, address: String, coefficient: String, wheel: String, weight: Number }
Continue readingIssue with querying dates with $gte and $lt
Issue I want to make searchDate API (I am using Express, Mongoose and Angular). I need to return list of data between two dates. Somehow it is working only if I hardcode date in $gte and $lt My api code:
Continue reading(MONGODB) How to remove referenced data when parent collection is deleted
Issue I have two schemas Folders and a model file as below. FolderSchema const mongoose = require(‘mongoose’) const {ObjectId} = mongoose.Schema const folderSchema = new mongoose.Schema({ title:{ type: String, }, belongsTo:{ type:ObjectId, ref:"Project" } }) module.exports = mongoose.model("Folder",folderSchema) modelFileSchema const
Continue readingServing Static file publically in nodejs :- Not Working
Issue In my nodejs server file, I am trying to server static folder the code goes as below :- server.js const express = require("express"); const app = express(); require("dotenv").config(); const cookieParser = require("cookie-parser"); const bodyParser = require("body-parser"); const { connectDB
Continue readingUnable to connect to Backend to nodejs and MongoDB
Issue I am Unable to connect to Backend While I am giving valid Credentials from front End I am Facing this error : POST http://127.0.0.1:5000/api/login 400 (Bad Request) I am Able to Generate the Token from Backend End , But
Continue readingWhy can't my AWS Lambda node JS app access my MongoDB Atlas cluster?
Issue Context : I have just created a Node.JS application and deployed it with the Serverless Framework on AWS Lambda. Problem : I would like that application to be able to access my (free tier) MongoDB Atlas Cluster. For this
Continue readingFile input always shows No file chosen
Issue I’m building a form using React & Nodejs & MongoDB, where you can fill the form and upload a file with some other text inputs. However, after i submit, i receive only text inputs in my database. The chosen
Continue readingSumming the values in mongoose
Issue I have a mongoose Schema which keeps track of 5 types of accidents every year . Now I also want a "Total Accidents" column which should simply sum up the values of those 5 columns and gets updated every
Continue readingMongoose find field with any value
Issue I have a find query like: person = await PersonSchema.find({ givenName: (gn == ‘none’) ? {} : gn, lastName: (ln == ‘none’) ? {} : ln, placeOfBirth: (pob == ‘none’) ? {} : pob, dob: { $regex: (dob ==
Continue readingNestJS Mongoose Schema Inheritence
Issue I am attempting to inherit Mongoose Schemas or SchemaDefitions within NestJS but I am not having much luck. I am doing this so I can share Base and Common Schema Definition Details such as a virtual(‘id’) and a nonce,
Continue readingGet a flat array of deeply nested items in MongoDB
Issue I am building a side project that uses a mongodb database. I am using the MERN stack to build out a web application with my data. I am using Mongoose to get data from my database on a NodeJS/Express
Continue readingHow can I update multiple documents in mongoose?
Issue I found the following script: Device.find(function(err, devices) { devices.forEach(function(device) { device.cid = ”; device.save(); }); }); MongoDB has the "multi" flag for an update over multiple documents but I wasn’t able to get this working with mongoose. Is this
Continue readingMultiple MongoJS calls in Node.js
Issue I am working on a node.js which has multiple steps with Mongo: Get a document Push a subdocument into the subarray and save Do an aggregation framework query to get the inserted subdocument Return it to the calling function
Continue readingHow to update a specific nested array inside a MongoDB document
Issue So I have a primary mongoDB object that has multiple documents nested within. I want to access a specific document in an array and modify one of its values. This is my document setup const sectionSchema = new mongoose.Schema({
Continue readingHow do I update a document in MongoDB using Mongoose
Issue I am creating a Car Booking Service. Here is the code for car Model. const mongoose = require(‘mongoose’); const CarSchema = new mongoose.Schema({ Name: { type: String, required: true }, Model: { type: String, required: true }, Year: {
Continue readingType is missing the following properties from type 'Schema<any, Model<any,any,any,any>, {}, {}>': add, childSchemas, clearIndexes, clone, and 37 more
Issue I’ve got a Mongoose on TypeScript, and it worked without interfaces and types defining, but when I decided to define types, the madness started. I’ve watched tons of manuals and topics and found nobody with a similar problem. I
Continue readingHow can I $push an item in two different fields, depending on the condition?
Issue I’m trying to receive the user location and store it in the database. Also, the user can choose if he wants to save all his previous locations or not. So I have created a boolean variable historicEnable: true/false. So
Continue readingModel.create() from Mongoose doesn´t save the Documents in my Collection
Issue I have created a sigle app with a Schema and a Model to create a Collection and insert some Documents. I have my todoModel.js file: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const todoSchema = new Schema({ username:
Continue readingCall function inside mongodb's aggregate?
Issue Collection: [ { _id: “Foo”, flag1: false, flag2: true, flag3: false }, { _id: “Bar”, flag1: true, flag2: false, flag3: true } ] My question is, is it possible to call a method inside aggregate query? aggregate({ $project: {
Continue readingHave changed mongodb's password several times. Does it affect previous projects where old password were used?
Issue I have changed mongodb’s user’s password from database access option. Every time I create a new project, I used to generate a new password for that. Now when I tested some previous projects I discovered some error saying MongoServerError:
Continue readingHow to find value in array of object in mongodb
Issue I want to get the value of a nested object within an array. I get the _id of the parent object, as well as the _id of the child object within the array, but I am not able to
Continue readingShow only records where an array of objects exists for logged in user
Issue Users can add multiple products and multiple users can request that product. When a user logs in, I want to show only products that have requests. I tried this which is supposed to firstly find products for the userId
Continue readingHow to add index weight on two id fields on MongoDB?
Issue I have a question regarding Mongo indexes for a $or request on two ObjectID fields. How can I make sure a search will first look at the first argument of the $or expression and only then if no match
Continue readingNot finding all items in a MongoDB TypeORM collection
Issue When using the find and findOne methods to get data from collection, it’s not returning all items in the collection. Collection.ts @Entity() export class Collection { @ObjectIdColumn() id !: string ; @Column() symbol !: string @Column() name !: string
Continue readingMy save data to MongoDB not functioning, is it because my searching is wrong?
Issue I’m trying to make a comparison function. If the value that I search is not exist, the new value will be save to the database. But all I get is 0 new data found. So the system decides to
Continue readingMongoServerError: unknown operator: $date
Issue I am trying to upsert a record in MongoDB from nodejs. The JSON I am trying to insert is: { _id: { ‘$date’: ‘2017-02-14T00:00:00Z’ }, dayType: ‘weekday’, endOfMonth: false, finEndOfMonth: false, _entity: [ ‘holiday’ ] } And I am
Continue readinghow join parent with child of the same collection mongodb
Issue I have the following collection called servicebyAff, where the parent collections are referenced { "_id" : ObjectId("53ed7efca75ca1a5248a281a"), "category" : {_id, ref: category}, "service" : {_id, ref: service} } I use $lookup for join the collection and the result was
Continue readingHow to filter the response from mongoDB, so nested arrays will include only items that meet a condition?
Issue My documents look like this { "_id": { "$oid": "62825f71005ce00c5f0235c1" }, "user": "jon", "roles": { "User": 2001, }, "STOCK ": [ { "sku": "BLACK-M", "productname": "BLACK", "sendout": 0, "recived": 1, "totalinstock": 40, "location": "B32", "_id": { "$oid": "62826016005ce00c5f0235c8" }
Continue readingNode – Router with multiple roles not working
Issue I’ve 4 roles: Normal User is auth, then Support, Admin, MasterAdmin Before i just had User and Admin and every request went fine. Now i added Support and MasterAdmin and try to get the the request when you are
Continue readingHow can I add custom keys to to mongoose schema item?
Issue I have a simple mongoose schema for a post: const postSchema = new mongoose.Schema({ title: { type: String, required: true, unique: true }, body: { type: String, required: true, unique: false } }) And I would like to add
Continue readingMongodb find created results by date today
Issue I have this query to get results on month. But I wanted to get the results of today. var start = new Date(2010, 11, 1); var end = new Date(2010, 11, 30); db.posts.find({created_on: {$gte: start, $lt: end}}); What is
Continue readingWhy spread operator is showing only the last entered data in a for loop?
Issue In a GET request I am using a spread operator in a for loop but it is showing only the last entered data only(data about seats) from the database. The GET request: router.get("/trip/single", async (req, res) => { if
Continue readingI can't replace the value of an array returned by mongoose
Issue I have a notifications.find query (mongoose) that returns multiple sheets Notification.find({id: id}, function(err, notifications){} I need to convert the timestamp values that are returned like that [ { _id: new ObjectId("12934193c51a231b0165425a"), userid: ‘62921df1c14a2eea0efa9399’, timestamp: 1653817696599, }, { _id: new
Continue readingWhy mongoose.model() is required to get data from MongoDB?
Issue I want to read data from the mongodb with mongoose, but every time it requires creating a model. Why? I thought model are just like templates to insert data to MongoDB. Can anyone describe what exactly mongoose.model() is and
Continue readingMongoDB findOneAndUpdate for value less than other value
Issue I can’t seem to figure out the right syntax to update (increment) a value by 1 if one value is smaller than another. Here’s some more details: Data Structure { "currentTask": 0, "maximumTask":10 } What I want to do
Continue readingMongoError: Can't extract geo keys
Issue I’m facing a mongoose error during post data updation. The error is: MongoError: Can’t extract geo keys I’ve tried to find the reason and the solution by searching on google but still I didn’t get any proper solution. Posts
Continue readingHow to populate data from another collections in mongoose?
Issue I want to populate the busNumber from bus Bus table to the trip table. Here’s the bus model const busSchema = new mongoose.Schema( { busNumber: { type: String, unique: true, required: true, }, seats: { type: Number, }, },
Continue readingMongoDB sets my database to 'test' automatically. How to change it?
Issue mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true}); const MyModel = mongoose.model(mymodel, new Schema({ name: String })); This creates a database named ‘test’ and a collection named ‘mymodel’. How to change the ‘test’ name of my database? Solution You have to change the connection
Continue readingMongodb Populate is not populating document in Node.js
Issue I am using typegoose and my Query and QueryRule models are as below. export class Query { @prop() queryRule: Ref<QueryRule>; } export class QueryRule { @prop() condition: Condition; @prop() rules: Ref<QueryRule | ChildRule>[]; } I am using the following
Continue readingI can not use env file variable values in my node project
Issue I have 2 variables in env file. For Port and mongoDB link. I have tried many solutions on the internet but i am not able to access the values in the listen method nor in database connection. Here is
Continue readingReferencing a schema, not a model
Issue I want to reference to a subdocument which is defined as a schema. Here’s the example: exam.model.js: const answerSchema = new mongoose.Schema({ text: String, isCorrect: Boolean, }); const questionSchema = new mongoose.Schema({ text: String, answers: [answerSchema], }); const examSchema
Continue readingHow to find and print array of objects in mongoDB document
Issue I have this document in mongoDB: { "_id": { "$oid": "628f739398580cae9c21b44f" }, "events": [ { "eventName": "Dans", "eventText": "Danse", "eventDate": "010101" }, { "eventName": "Spill", "eventText": "Spille", "eventDate": "020202" } ], "school": "Høyskolen Kristiania" } I am trying to
Continue readingcan someone tell me what this error mean?
Issue MongoError: cannot do raw queries on admin in atlas i tried to run : mongoose .connect( ‘mongodb+srv://yonco:mypassword@shop.iujhp.mongodb.net/?retryWrites=true&w=majority’ ) .then(result => { User.findOne().then(user => { if (!user) { const user = new User({ name: ‘yonc’, email: ‘yonc@rest.com’, cart: { items:
Continue readingUse database object after it has been created
Issue I’m trying to build an express server. In the app.js file I create the server and try to connect to my mongodb. import express from "express"; import dbo from "./db/conn.js"; const app = express(); app.listen(PORT, async () => {
Continue readingAssert in MongoDB 3.6 NodeJS driver? And how to use assert when using promise implementation?
Issue In MongoDB 3.6 driver, when I connect to mongodb host by callback, I follow the quickstart guide: From the example: const MongoClient = require(‘mongodb’).MongoClient; const assert = require(‘assert’); // Connection URL const url = ‘mongodb://localhost:27017’; // Database Name const
Continue readinghow can i sort data with a array element in mongodb without using unwind
Issue this is my sample data in this I have a userId and a array "watchHistory", "watchHistory" array contains the list of videos that is watched by the user : { "_id": "62821344445c30b35b441f11", "userId": 579, "__v": 0, "watchHistory": [ {
Continue readingedit a product from admin panel of eCommerce website project using nodejs with express.js, hbs and mongodb
Issue edit button <td> <a href="/admin/edit-product/{{this._id}}" class="btn btn-primary">edit</a> </td> router.get of edit product link that i given to the edit button var ProductHelpers = require(‘../helpers/product-helpers’) router.get(‘/edit-product/:id’,async (req,res)=>{ let product=await ProductHelpers.getProductDetails(req.params.id) console.log(product) res.render(‘admin/edit-products’,{product}) }) {{!–here i have rendered edit products page
Continue readingFetch/Find child collection using mongoose
Issue I am newbie in MongoDB. I am having some problem for nested collection. Suppose I have 3 different collections in mongodb. (1) classes (2) subjects and (3) chapter. Classes contain various class name, subjects contain different subject name for
Continue readingMongo suffering from a huge number of faults
Issue I’m seeing a huge (~200++) faults/sec number in my mongostat output, though very low lock %: My Mongo servers are running on m1.large instances on the amazon cloud, so they each have 7.5GB of RAM :: root:~# free -tm
Continue readingHow sort objects according to value from select element?- mongodb, nodejs
Issue I have to sort objects according to value from select option. How I should do this? //This is my select element in another file <select class="form-select" aria-label="Default select example"> <option id="sorting" selected>Sort by</option> <option value="1">Low to High price</option> <option
Continue readingNode JS + Mongo DB: ValidationError: User validation failed: username: Path `username` is required
Issue When I am trying to Save/Create a New Document (User) to Mongo DB using Mongoose, I am getting the following Validation Error in spite of providing all the Values with proper DataType: ValidationError: User validation failed: username: Path username
Continue readingDecrement a field and delete entire object if field's value reaches to 0 in MongoDB & Node.js
Issue I have array of objects like shopping list .for example i added 2 product to my list cart:[{id:1,quantity:15},{id:2,quantity:5}] i can increment and decrement quantities well , but what i want to do is when i decrement to 0 i
Continue readingHow to find multiple mongo db objects at once in node js
Issue i am trying to run a search , it is working fine with findOne and recieving data but when i use find it just return some headers and prototypes like this response i am getting code let data =
Continue readingHow to send formdata and image file in react native expo?
Issue Hi Everyone I want to send Formdata which includes some strings and an image file using react native expo to node server and mongo db can someone explain how can I do this using react native expo I have
Continue readingHow to run raw mongoDB commands using mongoose?
Issue I’m able to change the mongodb’s-sort-buffer-size using below command db.adminCommand({setParameter: 1, internalQueryExecMaxBlockingSortBytes: <limit in bytes>}) but, how to run the same command using mongoose library? Solution Try this: YourModel.db.db.admin().command({setParameter: 1, internalQueryExecMaxBlockingSortBytes: <limit in bytes>}, function (err,res) { console.log(res); });
Continue readingHow to find specific object from array in MongoDB
Issue Suppose I have this MongoDB document: { "_id": { "$oid": "628f739398580cae9c21b44f" }, "place":"Amsterdam", "events": [ { "eventName": "Event one", "eventText": "Event", "eventDate": "010101" "host":"Bob" }, { "eventName": "E2", "eventText": "e2", "eventDate": "020202" "host":"John" } ] } { "_id": {
Continue readingHow can I make an request params to mongo db from node js and swagger?
Issue What I have tried is to get all the data by createdBy param. createdBy has a user phone number value. controller exports.getLocation = asyncHandler(async (req, res, next) => { const createdBy = req.params.createdBy console.log(‘created’, createdBy) // its empty const
Continue readingThe options [useMongoClient] is not supported
Issue I am using mongodb-3.6.0. My express code is var promise = mongoose.connect(‘mongodb://localhost/myapp’, { useMongoClient: true }); On running the app I am getting the options [useMongoClient] is not supported. My mongoose version in ^5.0.0-rc0. Please help. Solution There is
Continue readingUpdate multiple documents and return all updated documents
Issue I am looking for a way to update many documents at once using mongoose and return all the modified documents. I tried with setting multi:true in update(). It is updating all matching documents but not returning any. Then I
Continue readingMongoDB Filter Nested Array in Node.JS
Issue I have a collection in MongoDB that looks something like this: [ { "machine": 1, "status": true, "comments": [ { "machine": 1, "status": false, "emp": "158", "comment": "testing the latest update" }, { "machine": 1, "status": false, "emp": "007",
Continue readingCreating documents that contain subdocuments with Mongoose
Issue I am trying to create my MongoDB Atlas database but the subdocument values are not coming through. Am i supposed to loop through them somehow ? Can’t find any solutions. Thanks Postman request: { "name" : "New Avengers", "items":
Continue readingIn nodejs, how do I traverse between embedded mongodb documents to get the values of their keys
Issue So, I have a different mongodb documents in relationship with one another. I want to be able to get access to the the different keys and their values starting with the parent document all the way down to the
Continue readingMongoose FInd and remove object from array of a document
Issue I have a document ‘Collection’: { name: {type: String, required: true, default: “Untitled Collection”}, movies: [ { the_id: {type: String}, movie_id: {type: String}, tmdb_id: {type: String}, original_title: {type: String}, release_date: {type:Date} }], author: {type: String},} I need to find
Continue readingThe pre hook is not working with find queries
Issue /*The pre hook is supposed to populate the teacher field, but for some reason it didn’t.Somehow when populate directly from the controller it works!*/ exports.getAssignment = catchAsync(async (req, res) => { const assignment = await Assignment.findById(req.params.id).populate( ‘teacher’ ); if
Continue readingMongoose how to count unique days in a month?
Issue i am working on a problem where in my database there supposed to be multiple entries from day to day. each entry includes a timestamp. the problem is im supposed to find how many days in each month a
Continue readingHow to return all documents that have a field that contains a given string
Issue I have a question, I’m creating a react app, using Node and MongoDB as back-end, and I’m trying to get all the documents from a collection, that have a field that contains a given string. This is how I
Continue readingMongooseError: Operation `users.findOne()` buffering timed out after 10000ms
Issue This is my connection file const connectDB = async () =>{ const conn = await new mongoose("mongodb+srv://nikunj:gadia7420@cluster0.94xph.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", { usenewurlparser:true, usecreateindex:true, usefindmodify:true, useunifiedtropology:true, urlencoded:true }) } module.exports = connectDB; this is my models file const userSchema = new mongoose.Schema({ username:{
Continue readingHow to access a preexisting collection with Mongoose?
Issue I have a large collection of 300 question objects in a database test. I can interact with this collection easily through MongoDB’s interactive shell; however, when I try to get the collection through Mongoose in an express.js application I
Continue reading