I need help with GET function on Firebase.
This code is intended to fetch data from firestorage:
app.get("/", async (req, res) => {
const snapshot = await admin
.firestore()
.collection("articles")
.orderBy("createdate", "desc")
.get();
const articles = [];
snapshot.forEach((doc) => {
const data = doc.data();
articles.push({ id: doc.id, ...data });
});
res.status(200).send(JSON.stringify(articles));
});
but how can I render that data by the tags if I call it
app.get("/:tag", async (req, res) => {
My data looks like this
collection - articles
- id
- title
- body
- tags - [0]culture
- [1]technology
i find the solution with this code
app.get("/tag/:tag", async (req, res) => {
await admin
.firestore()
.collection("articles")
.where("tags", "array-contains", req.params.tag)
.get()
.then((snapshot) => {
const articles = [];
snapshot.forEach((doc) => {
const data = doc.data();
articles.push({ id: doc.id, ...data });
});
return res.status(200).send(JSON.stringify(articles));
})
.catch((error) => {
res.status(404);
});
});
i use .where("tags", "array-contains", req.params.tag)
Related
committeeHead is a reference in collection users. I want to populate this id to get the specific data.
tried using Promise.all but I don't completely understand it and it isn't working for me.
const getAllCommittees = async (req, res, next) => {
try {
const committees = await db.collection("committees").get();
const committeesArray = [];
committees.forEach((doc) => {
committeesArray.push({ id: doc.id, ...doc.data() });
});
const committeesWithUsers = await Promise.all(
committeesArray.map((committee) => {
const user = db.collection("users").doc(committee.committeeHead).get();
return {
committee,
user,
};
})
);
res.json(committeesWithUsers);
} catch (err) {
console.log(err);
next(err);
}
};
I am very new to node.js/express/postman so please excuse me if this question is pretty rookie. I have the following code produced from following an online tutorial. I used Postman to test it. The problem is, when I add the line app.use(express.json), Postman is unable to send the post request. It gets stuck at "Sending request...". If I exclude that one line then the "Get" requests will work. Anyone know why... based on this code. This is all of it:
Thanks!
const Joi = require('joi'); // Put required modules at the top
const express = require('express');
const app = express();
app.use(express.json);
const courses = [
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' },
];
app.get('/', (req, res) => {
res.send('Hello world!!!');
});
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) => {
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course); // assigning the id on the server. return course to client
});
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
res.send(course);
});
app.put('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
course.name = req.body.name;
res.send(course);
});
app.delete('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const index = courses.indexOf(course);
courses.splice(index, 1);
res.send(course);
})
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.ValidationError(course, schema);
}
// PORT
const port = 3000;
app.listen(port, () => console.log(`listening on port ${port}...`));
You're issue is the json middleware (app.use(express.json);), which requires you to return valid JSON (Content-Type: application/json).
I got your sample running, by updating it to the following:
app.get('/', (req, res) => {
res.json({msg: 'Hello world!!!'});
});
Here's a working version: https://pastebin.com/06H6LCD2
Try:
app.use(express.json({ extended: false }));
I'm trying to learn testing with jest and supertest. I have this simple API:
app.get("/", (req, res) => {
res.json({ name: "bob" });
});
app.delete("/delete", async (req, res) => {
const result = await Todos.deleteOne({ _id: req.body.id });
res.send(result);
});
app.post("/add", (req, res) => {
const { item, status } = req.body;
const todo = new Todos({
item,
});
todo.save();
res.send(todo);
});
They all work. I also have these tests **which when individually run they all pass, but when I run them together the delete fails.
My logic is, when adding a post, I'm passing the id of the created post to the test so that the delete test can use
const request = require("supertest");
const app = require("../server");
describe("testing Todos API", () => {
let payload = { id: "6156c95c9ecf28237844489b" };
let item = { item: "test" };
it("get", (done) => {
request(app)
.get("/")
.expect(200)
.end((err, res) => {
expect(res.body).toEqual({ name: "bob" });
expect(res.body.name).toEqual("bob");
done();
});
});
it("post", (done) => {
request(app)
.post("/add")
.send(item)
.expect(200)
.end((err, res) => {
payload.id = res.body._id;
expect(res.body.item).toEqual(item.item);
done();
});
});
it("delete", (done) => {
request(app)
.delete("/delete")
.send(payload)
.end((err, res) => {
console.log(res.body);
expect(res.body.deletedCount).toEqual(1);
done();
});
});
});
But I get the error of error MongoServerError: E11000 duplicate key error collection and deletedCount is 0
product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};
I have an array of objects that is defined in mongoose schema as
blacklistGroup: {
userId: { type: String },
username: { type: String }
}
I can't figure out why it won't POST into mongodb.
I have a console.log that shows that it represents it's schema, but it never appears in mongodb? What am I doing wrong?
console.output
req.body.blacklistGroup
[ { userId: '5e2350c7f88cfb331c4f67de', username: 'artist1' },
{ userId: '5e20c5a139a92512cc7df63c', username: 'artist' } ]
[object Object]
app.js
app.post("/api/listings", checkAuth, (req, res, next) => {
console.log("req.body.blacklistGroup");
console.log(req.body.blacklistGroup);
let blacklistGroup = req.body.blacklistGroup;
console.log("req.body.blacklistGroup");
const post = new Post({
blacklistGroup: req.body.blacklistGroup,
});
//saves to database with mongoose
post.save().then(result => {
console.log(result);
res.status(201).json({
message: "Auction listing created successfully!",
postId: result._id
});
});
});
You can store all user at once. use mongoose insertMany
const Post = require('post'); //mongoose schema
app.post("/api/listings", checkAuth,(req, res, next) => {
console.log("req.body.blacklistGroup");
console.log(req.body.blacklistGroup);
let blacklistGroup = req.body.blacklistGroup;
console.log("req.body.blacklistGroup");
const blacklistGroup = req.body.blacklistGroup;
(async function(){
await Post.insertMany(blacklistGroup);
res.status(200).send('Ok');
})();
});
Or you can use
const Post = require('post'); //mongoose schema
app.post("/api/listings", checkAuth,async (req, res, next) => {
console.log("req.body.blacklistGroup");
console.log(req.body.blacklistGroup);
let blacklistGroup = req.body.blacklistGroup;
console.log("req.body.blacklistGroup");
const blacklistGroup = req.body.blacklistGroup;
await Post.insertMany(blacklistGroup);
res.status(200).send('Ok');
});
For More Here
You don't have an array of objects (or at least you don't want one), you have an object with two properties; userId and username. MongoDB is expecting JSON and it looks like you're trying to send it an array containing that object.
Try this:
let blacklistGroup = req.body.blacklistGroup[0];
To process an array of objects passed as req.body.blacklistGroup, you will have to iterate over it, define a new Post for each object and then send it. I think part of the confusion here is that your Schema is called blacklistGroup but it doesn't refer to a group, it refers to one entry.
const dbCalls = blacklistGroup.map(userObject => {
const post = new Post({
blacklistGroup: {
userId: userObject.userId,
username: userObject.username
});
return new Promise((resolve, reject) => {
post.save.then(() => {
resolve();
})
.catch(err => {
reject(err);
})
})
});
Promise.all(dbCalls).then(() => {
res.status(201).json({message: "Auction listings created successfully!"})
})
.catch(err => {
res.status(500).json({error: err})
});