Currently, I am developing an application using Node.js, specifically Express server-side and Vue client-side, with SQLite + Sequelize for managing the database.
One of the features of this app is that a user can create a post. While this functionality exists, I needed to establish a relationship so that each post can be linked to its author.
I managed to set up this relationship on the server-side using sequelize, and everything seems to be properly configured with the necessary table columns including foreign keys and references.
Now, my next task involves setting the current UserId
for the post before it is submitted. Below is the script element for the Vue component responsible for creating posts:
<script>
import PostService from '@/services/PostService'
export default {
data () {
return {
post: {
title: null,
body: null
}
}
},
methods: {
async submit () {
try {
await PostService.post(this.post)
} catch (err) {
console.log(err.response.data.error)
}
}
}
}
</script>
In order to access the 'user' object stored in the Vuex state after login, which includes the user's ID, I attempted to modify the post object as follows:
post: {
title: null,
body: null
UserId: this.$store.state.user.id
}
However, inserting this line caused issues with the component's functionality. Even trying to set it within the submit method also resulted in errors.
After exploring different approaches, such as potentially relying on Sequelize generating a setUser
method for the post model, I encountered challenges in implementing this feature successfully.
Despite various attempts, problems persisted, and any efforts to resolve them led to more errors or failures in the component's operation.
This dilemma arises especially when attempting to avoid setting any ID at all, which eventually triggers an error indicating that 'Post.UserID cannot be null,' disrupting the once smooth running application.
If anyone has insights or solutions to offer, especially considering my limited experience with Node development, I would greatly appreciate the assistance.
In other parts of the state, such as checking if a user is logged in properly through isUserLoggedIn
, there are no issues, and the application functions without crashing in those scenarios.