ObjectId id not of Function Type - reactjs

https://i.stack.imgur.com/7Tq6v.png
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")
const db = client.db();
const postItCollection = db.collection("postIts");
const result = await postItCollection.updateOne({_id: ObjectId(data.id)}, {$set:{positionX:data.y, positionY:data.x}});
console.log(result);
client.close();
res.status(201).json({message:"success"})
}
}
export default handler;
I'm attaching a picture just in case.
I've been looking for it for three hours, but I can't find the answer....
I don't think there's anyone on Earth who has the same problem as me....
I tried installed the "bson-objectid" library.
and "mongoose" Types property
import mongoose from "mongoose";
const { ObjectId } = mongoose.Types;
I've tried it, but I've seen same error of "method expression is not of function type"
Help me, all the masters of the earth.
From Newbie.
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")
const db = client.db();
const postItCollection = db.collection("postIts");
const result = await postItCollection.updateOne({_id: data.id}, {$set:{positionX:data.y, positionY:data.x}}); // <= if i not use ObjectId
console.log(result);
client.close();
res.status(201).json({message:"success"})
}
}
export default handler;
if I not use ObjectId I've got success messages but can't find id...
https://i.stack.imgur.com/XJOQH.png
I just want to find id in mongoDB and change data
PS. How can I see the image right away instead of the URL?
I looked at the other answers and did the same thing, but only the URL came out...

Oh i find Answer...!
It's new operation...
How do I search for an object by its ObjectId in the mongo console?
const result = await postItCollection.updateOne({_id: new ObjectId(data.id)}, {$set:{positionX:data.y, positionY:data.x}});

Related

FetchError: request failed

I have a bug, i'm trying to make his tutorial for twitter clone in nextjs+tailwindcss+typescript
https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha
1:42:05 / 3:17:52
I did exactly the same but i feel like my IDE or my nextJS version is making things different
import { Tweet } from "../typings"
export const fetchTweets = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
FetchError: request to https://localhost:3000/api/getTweets/ failed,
reason: write EPROTO 140020696905664:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
This error happened while generating the page. Any console logs >will be displayed in the terminal window.
import { Tweet } from "../typings"
export const fetchTweets = async () => {
if(global.window) {
const res = await
fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
}
Server Error Error: Error serializing .tweets returned from
getServerSideProps in "/". Reason: undefined cannot be serialized
as JSON. Please use null or omit this value.
If someone can help me <3 thanks
FIXED :
.env.local
i writed
NEXT_PUBLIC_BASE_URL=https://localhost:3000/
change https:// by http:// and yarn run dev again
NEXT_PUBLIC_BASE_URL=http://localhost:3000/

Firebase, trying to pull the collection based on a ID?

Basically, I have two collections per post. One with the comments on the post and one with the post information. The formula I wrote gives me the data of the post information. I want it to return both collections so I can map through the comment collection. but I cannot seem to figure out how to get it to send me to one level up basically. Any help would be appreicated!
const docRef = doc(db, "posts", postId);
useEffect(() => {
if(postId){
const getUsers = async () => {
const data = await getDoc(docRef)
console.log(data.data())
}
getUsers()
}
}, [])
The answer I was looking for is as follows!
const stepOne = collection(db,"posts")
const stepTwo = doc(stepOne,postId)
const stepThree = collection(stepTwo,"comments")
const stepFour = onSnapshot(stepThree,((snapshot)=>snapshot.docs.map((doc)=>console.log(doc.data()))))
Through this structure on the picture, comments are a collection nested inside posts, right? If so, then you cannot return a subcollection from a simple query on the parent document. Try fetching the post info first, then fetch the comments from an other query
this is for posts:
const docRef = doc(db, "posts", postId);
the path for comment will be
"posts/postId/comment"

How I can display only one object from API array Reactjs

How I can display only one object from [data.hits]? Ive tried map(), filter, also setRecipes([data.hits.recipe[0]]); etc ... and it doesn't work. Currently, it shows 10 objects on the website but I need only one. Thank you for any help.
const [recipes,setRecipes] = useState ([]);
useEffect(()=>{
getReciepes();
},[query]);
const getReciepes = async () => {
const response = await fetch (`https://api.edamam.com/search?
q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);}
I dont know how I did not notice this. Here is a simple solution :
const list=[...data.hits]
list.length = 1
setRecipes(list);
console.log(list);
}

Error 400 Bad Request while Uploading Image to firebase storage in React Native

I am working on react native project connected to firebase. I am =using firebase storage ad=nd trying to upload a file to firebase storage But I get following error.
{code: 400, message: "Bad Request. Could not access bucket quickbuy-a0764.appspot.com","status":"Access_Bucket"}
I tried configuring my permissions but did not work for me.
example of Image Uri I am providing to put() is as follows
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAk and so on
Now what should I do to resolve this issue?
let filename = values.images + Date.now();
let uri = values.images[0];
const uploadTask = storage.ref(`images/${filename}`).put(uri);
uploadTask.on("state_changed", (snapshot) => {
console.log(snapshot);
});
firebase.storage.Reference#put() accepts a Blob, Uint8Array or an ArrayBuffer. Because you are trying to upload a Data URI, which is a string, you need to use [firebase.storage.Reference#putString()`](https://firebase.google.com/docs/reference/js/firebase.storage.Reference#putstring).
To do this for a data URI, you would use:
someStorageRef.putString(uri, firebase.storage.StringFormat.DATA_URL);
Next, based on these lines:
const filename = values.images + Date.now();
let uri = values.images[0];
values.images is an array, which means that filename will end up being something similar to "[object Object],[object Object]1620528961143".
As I covered in this answer on your question yesterday, this is a poor way to generate IDs as it can lead to duplicates & collisions - use a Push ID instead.
const uri = /* ... */;
const rootRef = firebase.database().ref();
const filename = rootRef.push().key;
const uploadTask = storage.ref(`images/${filename}`)
.putString(uri, firebase.storage.StringFormat.DATA_URL);
uploadTask.on("state_changed", (snapshot) => {
console.log(snapshot);
});
Future Use with Version 9 of the SDK
import { getStorage, ref, uploadBytes } from "firebase/storage";
const uploadImage = async (values) => {
const filename = values.images + Date.now();
const uri = values.images[0];
// Create a root reference
const storage = getStorage();
// Create a reference to 'images/$filename.jpg'
const filesImagesRef = ref(storage, 1images/${filename}.jpg);
await uploadBytes(filesImagesRef, uri).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
}
Let us know how this works for you!

Creating Dynamic Routes using 'getStaticPaths' and 'getStaticProps' in NextJS

I am trying to create dynamic pages that show individual book details (.i.e. title/author) on a separate page based on a query string of the "id" for each book. In a previous question I asked, answers from users were very helpful and I have a much better understanding of how to use getStaticPaths and getStaticProps correctly. However, I am not quite there in my code for how to do this.
Here is the basic setup and context.
I am running NextJS 9.4 and would like to use a API endpoint instead of querying the database directly.
The book data is being pulled from a MongoDB Atlas Database and uses Mongoose
Documents in the MongoDB have a "_id" as a unique ID.
I have tried to incorporate and learn from existing Github examples and NextJS documentation but I still get the following error.
Error: A required parameter (id) was not provided as a string in getStaticPaths for /book/[id]
Here is the code I have so far. I have tried to keep the code as clean as possible for now.
export default function Book({ book }) {
return (
<article>
<h1>Book Details Page</h1>
<p>{book.title}</p>
<p>{book.author}</p>
</article>
)
}
export async function getStaticPaths() {
const url = `${baseUrl}/api/books/books`
const response = await axios.get(url);
const books = response.data
const paths = books.map((book) => ({
params: { id: book.id },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const url = `${baseUrl}/api/books/books/${params.id}`
const res = await axios.get(url)
const book = await res.json()
return { props: { book }}
}
The API endpoint looks like this:
import Book from '../../../models/Book';
import dbConnect from '../../../utils/dbConnect';
// conects to the database
dbConnect();
// This gets all the book from the database
export default async (req, res) => {
const books = await Book.find()
res.status(200).json(books)
}
Any support or feedback would be greatly appreciated. Once I get this working, I can hopefully be able to understand and help assist others in creating dynamic routes with NextJs. Thank you.
You can't make calls to Next.js API routes inside getStaticProps or getStaticPaths. These functions are executed at build time, so there is no server is running to handle requests. You need to make request to DB directly.
If you want to keep it clean you could create a helper module like allBooksIds() and keep DB query in a separate file.
See the same issue - API call in NextJS getStaticProps
Simply add toString() method in getStaticPaths because the book id is of type ObjectID("ID") if you do params: { id: book._id.toString() } it will convert ObjectID("ID") to type string which is accepted by getStaticPaths().The complete code for the nextjs part is below also update your API route as follows :-
The upper one is the API route the bellow one is Nextjs Page
import Book from '../../../models/Book';
import dbConnect from '../../../utils/dbConnect';
// conects to the database
dbConnect();
// This gets all the book from the database
export default async (req, res) => {
const books = await Book.find({})
res.status(200).json(books)
}
export default function Book({ book }) {
return (
<article>
<h1>Book Details Page</h1>
<p>{book.title}</p>
<p>{book.author}</p>
</article>
)
}
export async function getStaticPaths() {
const url = `${baseUrl}/api/books/books`
const response = await axios.get(url);
const books = response.data
const paths = books.map((book) => ({
params: { id: book._id.toString() },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const url = `${baseUrl}/api/books/books/${params.id}`
const res = await axios.get(url)
const book = await res.json()
return { props: { book }}
}
Hope this is helpful

Resources