match collection.find_one(doc! {"index": "1"}, None).await {
Ok(Some(user)) => println!("{:?}", user),
Ok(None) => println!("none"),
Err(err) => println!("{:?}", err),
};
i get an error
Error { kind: BsonDeserialization(DeserializationError { message:
"invalid type: map, expected a string" }), labels: {}, wire_version:
None, source: None }
Related
I'm working on a recipe website with React and using NedB as the database.
For each recipe, I want to store an image that I can retrieve later to be able to show it on the website but can't find any resources online to know how to do it.
This is my current code for initializing the database and inserting the elements in it
const nedb = require("nedb");
class Recipes {
constructor(recipeFilePath) {
console.log(recipeFilePath);
if (recipeFilePath) {
this.recipes = new nedb(recipeFilePath);
console.log("recipes connected to " + recipeFilePath);
recipeFilePath;
} else {
this.recipes = new nedb();
}
}
init() {
this.recipes.insert({
id: "1",
name: "carrot cake",
description: "home made here",
category: "cake",
prep_time: 20,
cook_time: 30,
serving: 4,
ingredients: [],
rating: [],
photo_location:""
});
this.recipes.insert({
id: "1",
name: "carrot cake",
description: "home made here",
category: "cake",
prep_time: 20,
cook_time: 30,
serving: 4,
ingredients: [],
photo_location:""
});
}
getAllEntries() {
return new Promise((resolve, reject) => {
this.recipes.find({}, function (err, entries) {
if (err) {
reject(err);
} else {
resolve(entries);
console.log("function all() returns: ", entries);
}
});
});
}
}
module.exports = Recipes;
Can anyone elaborate on how to store images?
I'm trying to add unit testing to my axios API calls
the .get call was easy to do... but when it comes to the POST/PUT/DELETE calls, I can't make it work.
here's what I tried (for POST)
my test:
const mockedAxios = axios as jest.Mocked<typeof axios>
...
test ('addGrocery()', async () => {
const newGrocery: IGrocery = {
_id: "1",
name: "Banana",
quantity: 2,
status: false,
}
const data = {
message: "Grocery added",
grocery: newGrocery,
groceries: [
{
_id: "1",
name: "Banana",
quantity: 2,
status: false,
},
{
_id: "2",
name: "Strawberry",
quantity: 1,
status: true,
}
]
}
mockedAxios.post.mockImplementationOnce(() => Promise.resolve(data))
await expect(addGrocery(newGrocery)).resolves.toEqual(data)
expect(axios.post).toHaveBeenCalled()
})
my API call:
export const addGrocery = async (formData: IGrocery): Promise<AxiosResponse<ApiDataType>> => {
try {
const grocery: Omit<IGrocery, "_id"> = {
name: formData.name,
quantity: formData.quantity,
status: false,
}
const apiUrl = baseUrl + '/add-grocery'
const saveGrocery: AxiosResponse<ApiDataType> = await axios.request({
method: 'POST',
url: apiUrl,
params: grocery
})
return saveGrocery
} catch (error: any) {
throw new Error(error)
}
}
and the controller:
const addGrocery = async (req: Request, res: Response): Promise<void> => {
try {
const query = req.query as unknown as Pick<IGrocery, "name" | "quantity" | "status">
const grocery: IGrocery = new Grocery({
name: query.name,
quantity: query.quantity,
status: query.status,
})
const newGrocery: IGrocery = await grocery.save()
const allGroceries: IGrocery[] = await Grocery.find()
res.status(201).json({
message: "Grocery added",
grocery: newGrocery,
groceries: allGroceries
})
} catch (error) {
throw error
}
}
I did a lot of research, pretty much everything I could find was only for the .get call, sometimes something just saying "change the mockeAxios.get to mockedAxios.post" (which is what I tried), but didn't work.
Getting the following error:
FAIL src/__tests__/API.test.tsx (16.851 s)
API tests
√ getGroceries() (6 ms)
× addGrocery() (5 ms)
● API tests › addGrocery()
expect(received).resolves.toEqual(expected) // deep equality
Expected: {"groceries": [{"_id": "1", "name": "Banana", "quantity": 2, "status": false}, {"_id": "2", "name": "Strawberry", "quantity": 1, "status": true}], "grocery": {"_id": "1", "name": "Banana", "quantity": 2, "status": false}, "message": "Grocery added"}
Received: undefined
59 | mockedAxios.post.mockImplementationOnce(() => Promise.resolve(data))
60 |
> 61 | await expect(addGrocery(newGrocery)).resolves.toEqual(data)
| ^
62 | expect(axios.post).toHaveBeenCalled()
63 | })
64 | })
I have a some code:
const taskId: number = req.body.taskId;
const text: string = req.body.text;
const task = await db.tasks.findOneAndUpdate(
{ taskId },
{ $push: { comments: [{
commentId: await db.getId(`task.${taskId}.commentId`),
taskId,
// #ts-ignore
author: Number(req.session.userId),
text,
timestamp: Date.now()
}] } }
).catch(e => {
console.error(e);
return res.status(400).json({ errors: [{ msg: "UNKNOWN_ERROR" }] });
});
if (!task) return res.json({ errors: [{ location: "query", msg: "NOT_FOUND", param: "taskId" }] });
return res.json(task);
But I have out (I skipped other properties):
{
...,
comments: [{
"timestamp": 1595833609905,
"_id": "5f1e7d09c1e15d4c8e0b71fa",
"taskId": 2,
"author": 435214391,
"text": "haha test comment"
}]
}
In comment property "commentId" is undefined.. But if I use
console.log({
commentId: await db.getId(`task.${taskId}.commentId`),
taskId,
// #ts-ignore
author: Number(req.session.userId),
text,
timestamp: Date.now()
})
I see the "commentId" property. Why it not saves in database? (Mongoose)
Okey, this is win. Error has been found in imports:
import TaskResponseSchema from './TaskResponse';
import TaskCommentSchema from './TaskResponse';
But okey:
import TaskResponseSchema from './TaskResponse';
import TaskCommentSchema from './TaskComment';
I geting the data back from my API in React from a post request and I get just the first object of the entire Array.prototype
My API for the upload:
router.post("/uploads", upload.any(), async (req, res) => {
try {
if (!req.files) {
res.send({
status: false,
message: "No file uploaded",
});
} else {
let data = req.files;
res.send({
status: true,
message: "Files are uploaded",
data: data,
});
}
} catch (error) {
res.status(500).send(err);
}
});
POSTMAN gives me back:
{
"status": true,
"message": "Files are uploaded",
"data": [
{
"fieldname": "uploads\n",
"originalname": "46335256.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "46335256-2020-08-04.jpg",
"path": "client/uploads/46335256-2020-08-04.jpg",
"size": 19379
},
{
"fieldname": "uploads\n",
"originalname": "120360358.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "120360358-2020-08-04.jpg",
"path": "client/uploads/120360358-2020-08-04.jpg",
"size": 78075
}
]
}
perfect!
this is my function in React to upload
const uploadFiles = () => {
uploadModalRef.current.style.display = "block"
uploadRef.current.innerHTML = "File(s) Uploading..."
for (let i = 0; i < validFiles.length; i++) {
const formData = new FormData()
formData.append("images", validFiles[i])
axios
.post("http://localhost:5000/api/db/uploads", formData, {
onUploadProgress: progressEvent => {
const uploadPercentage = Math.floor(
(progressEvent.loaded / progressEvent.total) * 100
)
...// code for graphic upload
},
})
.then(resp => {
console.log(resp.data.data)
resp.data.data.map(item => {
console.log(item)
})
})
.catch(() => {
... // code
}
}
and with this I get (from the console):
[{…}]
0:
destination: "client/uploads/"
encoding: "7bit"
fieldname: "images"
filename: "46335256-2020-08-04.jpg"
mimetype: "image/jpeg"
originalname: "46335256.jpg"
path: "client/uploads/46335256-2020-08-04.jpg"
size: 19379
__proto__: Object
length: 1
__proto__: Array(0)
is an array(if I map it works) but with just the first object.
How is it possible ??
I tried even with async/await but nothing changes
Where I'm mistaking?
Thanks!
I have built an API with JSON-server and I am trying to fetch the data from it using React-Apollo Client.
I'm trying to log the data from API on the console with Query tag, restructure and print the data variable using console.log().
I have no idea why the function is getting print via console.log().
I have the current setup:
JSON server is running on PORT 4000
Server is running on PORT 5000
Client is running on PORT 3000
I am already using CORS tool
Below is my component:
const BOOKS_QUERY = gql`
query BooksQuery {
books {
title
author
editionYear
}
}
`;
<Query query={BOOKS_QUERY}>
{({ loading, error, data }) => {
if (loading) return <h4>Loading...</h4>;
if (error) console.log(error);
console.log(data);
return <h1>test</h1>;
}}
</Query>
The content below is code for my schema:
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLInt },
title: { type: GraphQLString },
author: { type: GraphQLString },
editionYear: { type: GraphQLInt }
})
});
//Root Query
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
return axios.get('http://localhost:4000/books').then((res) => res.data);
}
},
book: {
type: BookType,
args: {
id: { type: GraphQLInt }
},
resolve(parent, args) {
return axios.get(`http://localhost:4000/books/${args.id}`).then((res) => res.data);
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
API:
{
"books": [
{
"id": "1",
"title": "Java How To Program",
"author": "Deitel & Deitel",
"editionYear": "2007"
},
{
"id": "2",
"title": "Patterns of Enterprise Application Architecture",
"author": "Martin Fowler",
"editionYear": "2002"
},
{
"id": "3",
"title": "Head First Design Patterns",
"author": "Elisabeth Freeman",
"editionYear": "2004"
},
{
"id": "4",
"title": "Internet & World Wide Web: How to Program",
"author": "Deitel & Deitel",
"editionYear": "2007"
}
]
}
I only expect the API data to be logged on console.
Later I will render that data on screen.