Connecting to a particular mongo collection of a mongo atlas clustor
I had successfully imported the data from my local system to mongo atlas. On connecting with the cluster0
using Mongo Compass
, I got this connection string.
mongodb+srv://mohit_maroliya:<password>@cluster0.ttieq.mongodb.net/test
When I copied the string and connected using MongoShell
, it directed me to this page where it shows 3 DBs. (admin, chesswear, local)
I want to connect this chesswear
database to my nextjs app. So the connection URI in my env.local
file should be changed from
MONGO_URI=mongodb://localhost:27017/chesswear
TO
MONGO_URI=mongodb+srv://mohit_maroliya:<password>@cluster0.ttieq.mongodb.net/test
What is my doubt?
I wonder if I put the mongodb+srv://mohit_maroliya:<password>@cluster0.ttieq.mongodb.net/test
MONGO URI, will it work because it is not selecting any database from the 3 it will encounter.
I just wanted to know what path I had to put in the MONGO_URI
to be able to connect to the remote database.
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
delete a table form a database using laravel command
i need to delete a database table using laravel artisan command . not like this command php artisan migrate:rollback --step=5
i need to create like this route or controller code .
Route::get('/clear/database', function () {
Artisan::call('cache:clear'); return redirect('/');
});
. i also try public function dd()
{ Schema::drop('table_name'); }
but it not working . gives me error like this SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table
table_name
)no foreign key for the table . what should i do ?
thanks in advance!
-
How to bring data frame into single column from multiple columns in python
I have data format in these multiple columns. So I want to bring all 4 columns of data into a single column.
YEAR Month pcp1 pcp2 pcp3 pcp4 1984 1 0 0 0 0 1984 2 1.2 0 0 0 1984 3 0 0 0 0 1984 4 0 0 0 0 1984 5 0 0 0 0 1984 6 0 0 0 1.6 1984 7 3 3 9.2 3.2 1984 8 6.2 27.1 5.4 0 1984 9 0 0 0 0 1984 10 0 0 0 0 1984 11 0 0 0 0 1984 12 0 0 0 0
-
On the time function of database
When I use Kingbase database in Windows environment, I find that the time function returns the same value in the same transaction. How do I deal with it
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
Error message : MongoServerError: bad auth :Authentication failed
What is the reason behind this error? this code I am using to connect to DB.
const uri =`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.xft2s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
-
In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved
//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs'); //addDino module.exports.addDino = (req, res) => { var name = req.body.name; var type = req.body.type; var height = req.body.height; var weight = req.body.weight; var Period = req.body.Period; req.checkBody('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors) return res.status(400).send({ message: 'Name is Required' }); else { let newDino = { name: name, type: type, height: height, weight: weight, Period: Period } Dinosaur.addDino(newDino, (err, result) => { if (err) { if (err.name) return res.status(409).send({ message: name + ' Already Exist' }); else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url }); else return res.json(err, "Server Error"); } else { return res.status(200).send({ message: "Done" }); } }); } }
// Model
var mongoose = require('mongoose'); //dinosaur schema var DinosaurSchema = mongoose.Schema({ name: { type: String, unique: true }, type: { type: String }, height: { type: Number }, weight: { type: Number }, Period: { type: String } }); var Dinosaur = mongoose.model('dinosaur', DinosaurSchema); //add module.exports.addDino = (query, callback) => { Dinosaur.create(query, callback); }
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
-
Unexpected token ')' in D:\Mridul\Codes\js\API BASED\Anime Quote\views\info.ejs while compiling ejs
So I want to display MongoDB data in HTML so I used the EJS template but this is the error it is showing . I can't seem to figure out where the problem is, IS it in the EJS file or in the data?
Here is the EJS template
` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Information</title> </head> <body> <h1>Information</h1> <ul class="savage"> <%Content.forEach(data=>{%> <p><%=data.Name%></p> <p><%=data.Description%></p> <p><%=data.Birthday%></p> <p><%=data.Alternative_Name%></p> <p><%=data.Backstory%></p> <p><%=data.Anime_OR_Manga>%></p> <%})%> </ul> <h2>Add a Info</h2> </body>`
Here is the server.js
const express=require('express'); const cors=require('cors'); const app= express(); const PORT =8000; let ejs=require('ejs'); const mongoose=require('mongoose'); app.set('view engine','ejs'); const uri="mongodb+srv://mridultiwar:mridultiwari@cluster0.ub68a.mongodb.net/SearchBAckend?retryWrites=true&w=majority"; mongoose.connect(uri); const savageSchema=new mongoose.Schema({ Name:String, Description:String, Birthday:String, Alternative_Name:String, Backstory:String, Anime_OR_Manga:String, }) const Savage=mongoose.model('savages',savageSchema) // const client=new MongoClient(uri) // MongoClient.connect(uri); //let content=document.getElementById('addedinfo'); // app.get('/view',function(req,res){ // db.serialize(()=>{ // db.run() // }) // }); app.get('/info',function(req,res){ Savage.findOne({},'Izuku', function(err,data){ console.log(data); res.render('info.ejs',{ Content:data }) }) })
And here is the data i wanna retrieve
{"_id":{"$oid":"6275e6402c1944072bcb4646"}, "Name":"Izuku", "Description":"Izuku 'Deku' Midoriya is the main protagonist of the manga and anime My Hero Academia and is in Class 1-A at U.A. High School." ,"Birthday":"July 15,2010 Cancer", "Alternative_Name":"Deku", "Backstory":"In a world where most humans on the planet develop superpowers soon after they're born, a boy named Izuku Midoriya was one of the few who never developed any powers. As a child, Izuku dreamed to become a superhero like his idol, All Might, after he developed his power, or 'Quirk'. As such, he was devastated once he learned that he'd never get a quirk. His lack of a Quirk made him a prime target for bullying, but Izuku still wanted to be a hero, and planned to go to the prestigious U.A. hero academy. Ten months before the entrance exams for U.A. started, Izuku came face to face with All Might after he was saved from a villain by him. Izuku asked All Might if it was possible for someone without a quirk to be a hero, but he responded by telling him that he needed realistic dreams. Soon after, the same villain from before ended up breaking free and attacking one of Izuku classmates. Despite not having a quirk, Izuku still tried to save his classmate. While he didn't stop the villain, he did give All Might enough time to defeat them himself. After this, All Might decided that Izuku had the potential to become a hero, with his help. He decided that he would grant Izuku his own Quirk to help him achieve his dreams. After ten months of training, All Might passed his Quirk, One For All, down to Izuku. Izuku then managed to pass the entrance exam, and officially enrolled in U.A, taking on the Hero name 'Deku", "Anime_OR_Manga": "Boku No Hero Academia"
I tried looking for the similar error in stack overflow, but i can't seem to find it Here is the error shown:
{ _id: new ObjectId("626e9ade4b9416e659a5f4e1") } SyntaxError: Unexpected token ')' in D:\Mridul\Codes\js\API BASED\Anime Quote\views\info.ejs while compiling ejs If the above error is not helpful, you may want to try EJS-Lint: https://github.com/RyanZim/EJS-Lint Or, if you meant to create an async function, pass `async: true` as an option. at new Function (<anonymous>) at Template.compile (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:673:12) at Object.compile (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:398:16) at handleCache (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:235:18) at tryHandleCache (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:274:16) at View.exports.renderFile [as engine] (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\ejs\lib\ejs.js:491:10) at View.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\view.js:135:8) at tryRender (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\application.js:640:10) at Function.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\application.js:592:3) at ServerResponse.render (D:\Mridul\Codes\js\API BASED\Anime Quote\node_modules\express\lib\response.js:1017:7)
-
mongoose save internal documents creating a document that contains a document
Im learning mongoose and i have a question how to save several documents:
// Product.js const categorySchema = mongoose.Schema( { name: String }, { collection: "categories" } ); const productSchema = mongoose.Schema( { name: String, category: categorySchema }, { collection: "products" } ); modules.exports = mongoose.model("Product", productSchema);
The idea is that when I create a product this way
const Product = require("./Product.js") const product = new Product({name: 'Soccer Ball', category: {name: "Sports"}) await product.save()
i want to get a document in the collection products and also a document in the collection categories
how can it be possible
thanks in advance
PD : Im getting this but category is not save in the collection
{ "msg": "Product created succesfully", "ok": true, "product": { "name": "Soccer ball", "category": { "name": "Sports", "_id": "6275df4c8149967bea21e7c0" }, "_id": "6275df4c8149967bea21e7bf", "__v": 0 } }
-
Mongoose findByIdAndUpdate - not updating selection
I'm following a tutorial with MERN (source code here: https://github.com/Nikhilthadani/Book-Store-With-MERN-Stack/blob/Backend/controllers/books-controller.js)
Everything seems fine with the initial routing (get & post) , until we added a route for updating entries (PUT) in mongoDB.
Here is my function for the PUT
//book-controller.js const updateBook = async (req, res, next) => { const id = req.params.id; const { name, code } = req.body; let book; try { book = await Book.findByIdAndUpdate(id, {new: true}, { name, code, }); book = await book.save(); } catch (err) { console.log(err); } if (!book) { return res.status(404).json({ message: "Unable To Update By this ID" }); } return res.status(200).json({ book }); };
Here is my Schema
// Book.js const mongoose = require('mongoose') const bookSchema = new mongoose.Schema({ name: { type: String, required: true, }, code: { type: Number, required: true, }, }); module.exports = mongoose.model("Book", bookSchema);
When I try to test this function in Postman, the GET request returns the entry that I'm attempting to update just fine.
Confirming database entry with Get
However, after testing PUT, the particular entry I'm trying to update will remain unchanged, despite no output errors
-
Apollo `useMutation()` stuck loading inside Next.js component
The following form component in Next.js submits without errors but never completes the mutation. Instead it get's stuck in the
loading
state.import React, { useState } from "react"; import { gql, useMutation } from "@apollo/client"; import { ApolloClient, InMemoryCache } from "@apollo/client"; const client = new ApolloClient({ ssrMode: true, uri: process.env.API_URL, cache: new InMemoryCache(), }); const CREATE_COMMENT = gql` mutation CreateComment( $username: String! $comment: String! ) { createComment( data: { username: $username, comment: $comment } ) { id username comment } } `; export default function SocialForm() { const [commentName, updateCommentName] = useState(""); const [commentDescription, updateCommentDescription] = useState(""); const [createComment, { data, error, loading }] = useMutation( CREATE_COMMENT, { client } ); const handleFormSubmit = async () => { await createComment({ variables: { name: commentName, comment: commentDescription }, }); }; if (loading) return "loading..."; if (error) return <p>error text :(</p>; return ( <> <form onSubmit={async (e) => { e.preventDefault(); await handleFormSubmit(); }} className="social-form" > <input required onChange={(e) => updateCommentName(e.target.value)} type="text" placeholder="Full Name" className="" /> <textarea required maxLength="280" onChange={(e) => updateCommentDescription(e.target.value)} className="w-full" name="comment" rows="5" placeholder="Leave your thoughts and images at the moment" /> </form> </> ); }
Also the server side mutation with this exact same schema runs correctly inside Apollo playground and I'm using Keystone.js to auto generate the schema.
-
NextJS: Error serializing `.data.data` returned from `getServerSideProps`
I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use
getServerSideProps
to get data from the server on load, so I've got the following:myProject/pages/category/new.js
:export default function AddNewCategory(data) { ... } export const getServerSideProps = async () => { const data = await getAllCategories(); console.log(await data) return { props: { data: { data } } }; };
myProject/api/category.js
:import axios from "axios"; // getAllCategories returns a list of all active categories export const getAllCategories = async() => { axios.get("http://127.0.0.1:8080/api/v1/categories") .then(function (response) { console.log(response.data) return response.data; }) .catch(error => { console.error("error") console.log(error) }) }
As you can see I've got a print statement in
getAllCategories
which prints:{ data: [ { id: 1, name: 'Pop', slug: 'pop', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:00-04:00', updated_at: '2022-05-03T19:50:00-04:00', deleted_at: null }, { id: 3, name: 'Pop 2', slug: 'pop-2', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:24-04:00', updated_at: '2022-05-03T19:50:24-04:00', deleted_at: null } ] }
yet I'm getting the following error:
error - Error: Error serializing
.data.data
returned fromgetServerSideProps
in "/category/new". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.I saw around that I should try to convert the data to string and then back to json:
return { props: { data: JSON.parse(JSON.stringify(data)) } };
but when I do this I'm getting a different error:
error - SyntaxError: Unexpected token u in JSON at position 0
I'm using
next@12.1.5
Any idea what's going on?
-
I am having problem in development mode with NextJS but it works perfect on production. Warning: Prop `className` did not match. Server
This is the problem I am using A React framework & component library for building web user interfaces at Volvo Cars and the engine for this css-in-js. Please check the photo. Thank you!