How to push data in MongoDB's array with mongoose - arrays

I have an empty array in MongoDB
And I want to push the Id in it.
router.put(
"/like/:id",
(req, res) => {
User.findOne({ _id: req.user._id }).then(data => {
if (data) {
Post.update(
{ _id: ObjectId(req.params.id) },
{ $push: { likes: req.user._id } }
);
}
});
}
);
This code is not working on how I achieve this.

router.put (
"/addlike/:id",
passport.authenticate("jwt", {
session: false
}),
(req, res) => {
// use try-catch
try {
User.findOne({ _id: req.user._id }).then(data => {
if (data) {
Post.findOneAndUpdate(
{ _id: ObjectId(req.params.id) },
{ $push: { likes: req.user._id },
{ "new": true, "upsert": true} }
);
}
});
} catch(err){
// handle error
console.log('Error => ', err);
}
}
);
I have tested this in my local system ... working fine

Related

Internal server error 500 react post to firebase

I'm getting a 500 error when posting to my firebase database. However, when I post via postman, it works fine, thus I'm having a lot of trouble debugging this. For the moment, I've hardcoded the categoryId and also the newRow, to make sure there wasn't a problem with my state somehow.
I think the handleSubmit is the only relevant function
handleSubmit = (event) => {
event.preventDefault();
const categoryId = "1RegisterInfo";
const newRow = {
index: "3",
body: "this.state.body",
dataType: "this.state.dataType",
visit: "test",
};
this.props.postRow(categoryId, { newRow });
};
action
export const postRow = (categoryId, rowData) => (dispatch) => {
dispatch({ type: "LOADING_UI" });
axios
.post(`/category/${categoryId}`, rowData)
.then((res) => {
dispatch({
type: "POST_ROW",
payload: res.data,
});
dispatch(clearErrors());
})
.catch((err) => {
dispatch({
type: "SET_ERRORS",
payload: err.response.data,
});
});
};
cloud function
exports.postRow = (req, res) => {
if (req.body.body.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.index.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.dataType.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.visit.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
const newRow = {
index: req.body.index,
dataType: req.body.dataType,
visit: req.body.visit,
body: req.body.body,
createdAt: new Date().toISOString(),
categoryId: req.params.categoryId,
disapproveCount: 0,
approveCount: 0,
};
db.doc(`/categories/${req.params.categoryId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: "Category not found" });
}
})
.then(() => {
return db.collection("rows").add(newRow);
})
.then(() => {
res.json(newRow);
})
.catch((err) => {
console.log(err);
res.status(500).json({ error: "Something went wrong" });
});
};
Any help appreciated!
You're not sending the right payload.
{ newRow }
is the same as
{
newRow: {
index: '3',
body: this.state.body,
dataType: this.state.dataType,
visit: 'test',
},
}
You're passing the above data in the request body and so req.body.body is undefined causing req.body.body.trim() to fail.
this.props.postRow(categoryId, { newRow })
should be
this.props.postRow(categoryId, newRow)
I would recommend using Joi or something similar to validate the request payload before trying to do any other operation.

React Context - Post Like / Unlike feature

I am building post like / unlike feature using React context, but I have no idea what to do in reducer to update UI. Currently when I click like / unlike button, ui doesn't update instantly, have to refresh page to see the update.
backend logic
exports.likePost = async (req, res) => {
try {
const result = await Post.findByIdAndUpdate(
req.body.postId,
{
$push: { likes: req.body.userId },
},
{ new: true }
);
return res.json(result);
} catch (err) {
console.log(err.message);
}
};
exports.unlikePost = async (req, res) => {
try {
const result = await Post.findByIdAndUpdate(
req.body.postId,
{
$pull: { likes: req.body.userId },
},
{ new: true }
);
return res.json(result);
} catch (err) {
console.log(err.message);
}
};
component
{post.likes.includes(loggedInUser._id) ? (
<IconButton
color="secondary"
component="span"
onClick={() => unlikePost(loggedInUser._id, post._id)}
>
<Like />
</IconButton>
) : (
<IconButton
color="secondary"
component="span"
onClick={() => likePost(loggedInUser._id, post._id)}
>
<Unlike />
</IconButton>
)}
context
const initialState = {
posts: [],
};
// Like post
const likePost = async (userId, postId) => {
try {
const res = await axios.put(
`/api/posts/like`,
{ userId, postId },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
dispatch({ type: "LIKE_POST", payload: res.data });
} catch (err) {
console.log(err);
}
};
// Unlike post
const unlikePost = async (userId, postId) => {
try {
const res = await axios.put(
`/api/posts/unlike`,
{ userId, postId },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
dispatch({ type: "UNLIKE_POST", payload: res.data });
} catch (err) {
console.log(err);
}
};
reducer
case "LIKE_POST":
return {
...state,
posts: // ???
),
};
case "UNLIKE_POST":
return {
...state,
posts: // ???,
};
What should be the logic for reducer?
Something like this:
case "LIKE_POST":
return {
...state,
like: action.likeValue,
};
case "UNLIKE_POST":
return {
...state,
unlike: action.unlikeValue,
};
When you want to change the value:
dispatch({ type: "LIKE_POST", likeValue: res.data });
dispatch({ type: "UNLIKE_POST", unlikeValue: res.data });
In your initial state:
const initialState = {
posts: [],
like: [],
unlike: [],
};
Here is a good explanation, which helped me: link

I have data on the front end but it's undefined in the back end

Hello guys i have a problem with my data on the fetch indeed on the front side i do this to fetch my data:
() => {
const data = {clubChoix: element.nomClub};
const options = {
method: 'POST',
body: data,
};
fetch('http://localhost:8080/inscription/choixclub', options)
.then((response) => {
return response.json();
})
.then(
(responseData) => {
console.log(responseData);
},
(err) => {
console.log(err);
},
);
})
And the i put a console.log to make sure that what i send is real
(console.log(element.nomClub),
The result of this one is:
LOG: Nimes Olympique
In my thought the "const data = {choixClub: element.nomClub};" in the data is like a req.body.clubChoix but in the back end so why when i console log it the req.body it's undefined ?
in case you want to see my back end there it is:
choixClub: (req, res) => {
User.updateOne(
{ _id: "5f47a46e36588f5e2a1e4f35" },
{
$set: {
club: req.body.clubChoix,
},
},
(err) => {
if (err) {
console.log(err);
res.json({ message: "une erreur s'est produite" });
} else {
console.log(req.body.clubChoix);
res.json({ message: "Votre club a bien été enregistré" });
}
}
);
},

Cant patch mongoDB/express

I have a react, redux and mongoDB app with a users collection, each user has a favorites array which I want to update with a patch everytime a user adds a favorite element, but my patch method always returns error with a 404 (Not Found). Here's my code:
Action:
export const saveToUser = info => dispatch => {
axios
.patch('api/users', info)
.then( res => {
dispatch({
type:SAVE_TO_USER,
payload:info
})
dispatch( getUsers() )
}).catch( err => console.log(err))
}
users.js
router.patch('/:id', (req,res) => {
User.update({ googleId: req.body.googleId },
{ $push: { favorites: req.body.site } })
});
server.js
const users = require('./routes/api/users')
app.use('/api/users', users);
Fixed myself. My query was wrong, it shoud be:
router.patch('/', (req,res) => {
User.findByIdAndUpdate(
{ _id: "userId" },
{ favorites: ["Here something"] },
function(err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
});

Axios > Express.router – Update(.put) method returning 404

I am trying to finish building the last CRUD method of my App. (C, R and D) all done. But updating seems to be proving bothersome. I have a function which combines the object ID with the new content to update with. I am getting Error: Request failed with status code 404printed to the console.
I think I'm failing to reach the database item using the ID.
Function which gathers the data and initiates the request
handleClick(e) {
e.preventDefault()
const data = {
id: this.props.sid, //someuniqueid
body: {
name: this.state.name, //foo
details: this.state.details, //bar
content: this.state.content, //baz
},
}
api
.updateSnippet(data)
.then(result => {
this.setState({
name: '',
details: '',
content: '',
message: `'${this.state.name}' has been created`,
})
setTimeout(() => {
this.setState({
message: null,
})
}, 2000)
console.log('UPDATE DATA SUCCESS!')
})
.catch(err => this.setState({ message: err.toString() }))
}
api.js - uses axios to fire the request (this may be where I am failing).
import axios from 'axios'
const service = axios.create({
baseURL:
process.env.NODE_ENV === 'production'
? '/api'
: 'http://localhost:5000/api',
withCredentials: true,
})
const errHandler = err => {
console.error(err)
if (err.response && err.response.data) {
console.error('API response', err.response.data)
throw err.response.data.message
}
throw err
}
export default {
service: service,
updateSnippet(data) {
console.log(data.id) //someuniqueid
console.log(data.body) //{name: "foo", details: "bar", content: "baz"}
return service
.put('/snippets' + data.id, {
data: data.body,
})
.then(res => res.data)
.catch(errHandler)
},
}
Snippet.js (schema)
const mongoose = require('mongoose')
const snippetSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'The snippet name is required'],
minlength: 1,
},
details: {
type: [String],
default: [],
},
content: {
type: String,
},
})
const Snippet = mongoose.model('Snippet', snippetSchema)
module.exports = Snippet
Relevant route in "routes/snippets.js" - This could also be where I am falling over
router.put('/', function(req, res) {
console.log(req.body)
Snippet.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content,
},
{ new: true },
function(err, response) {
if (err) {
console.log('we hit an error' + err)
res.json({
message: 'Database Update Failure',
})
}
console.log('This is the Response: ' + response)
}
)
})
You are sending the id in the url, so you need to parse it from req.params.id.
I also returned response.
routes/snippets.js
router.put("/:id", function(req, res) {
console.log(req.body);
Snippet.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content
},
{ new: true },
function(err, response) {
if (err) {
console.log("we hit an error" + err);
return res.json({
message: "Database Update Failure"
});
}
return res.send(response);
}
);
});
Also you need to update this line in api.js. Just add / after snippets
.put('/snippets' + data.id, { =>
.put('/snippets/' + data.id, {

Resources