Adding mongoose schema model to express results in error 500 - express

I have react app that stores data via axios to a mongoose server. It worked perfect until I wanted to add an extra schema for different data. My schema models are separated so I thought to just add another one called PartyList.js.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Define collection and schema for Items
var PartyList = new Schema({
name: {
type: String
},
song_id: {
type: String
},
port: {
type: Number
}
},{
collection: 'party'
});
module.exports = mongoose.model('PartyList', PartyList);
This is the code in my app.js.
const config = require('./database/DB');
const ServerPortRouter = require('./routes/ServerPortRoutes');
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database' +err)
});
app.use('/serverport', ServerPortRouter);
This is how I import it and try to run it (called ServerPortRoutes.js). After running a part of my application that uses this route I get a 500 (Internal Server Error). My server tells me ReferenceError: PartyList is not defined which is defined 3 lines above.
const ServerPort = require('../models/ServerPort');
const PartyList = require('../models/PartyList');
ServerPortRouter.route('/add-party').post(function (req, res) {
const PartyList = new PartyList(req.body);
PartyList.save()
.then(PartyList => {
res.json('Server added successfully');
})
.catch(err => {
res.status(500).send("unable to save to database");
});
});

The problem looks to be you are redefining a const . In your route change to const partyList = new PartyList(req.body); Then use partyList as your variable

Related

Graphql studio getting null data

I am new to Graphql, express, and Apollo.
Expected result: I am trying to consume data from JSON file data and get results in the studio.
Actual Result: Getting "null" data instead.
I am attaching my code snippets and problems below
Refer the following:
Let me show you the code:
directory structure:
MOCK_DATA.json
I am just keeping data small for testing the concept.
[{
"name": "Leanne Graham",
"username": "Bret"
},
{
"name": "Rohit Sharma",
"username": "rohituid"
}]
index.js
As per my understanding, The significance of the file is wiring up the express middle wire with the Apollo server. Tried to make this file in a way that it will be hardly touched.
Other than that, I have the async function was required to fix Apollo Server await server.start bug .
I am creating apollo server
const { ApolloServer } = require("apollo-server-express");
const { typeDefs } = require("./Schema/TypeDefs");
const { resolver } = require("./Schema/Resolver");
const express = require("express");
const app = express();
const PORT = 3001;
async function createApolloServer() {
//passing into apollo constructor
const server = new ApolloServer({
typeDefs,
resolver
});
//instantiatiating the apollo server
await server.start();
//this will install the apollo server on express app
server.applyMiddleware({ app });
}
createApolloServer();
//console.log(resolver);
app.listen(PORT, () => {
console.log('Server is running on : http://localhost:3001/graphql');
Schema:
TypeDefs.js
const { ApolloServer, gql } = require("apollo-server");
//below is known as tagged template literal
const typeDefs = gql`
type User {
name: String
username: String
}
#Queries -like get in REST World
type Query {
getAllUsers: [User]
}
`;
//console.log(typeDefs);
module.exports = { typeDefs };
Resolver.js
const userData = require("../MOCK_DATA.json");
//const userData = require("../FakeData.js");
// this is resolver map -> javascript object
//using arrow function
/*
below arrow function equivalent to using function like:
function getAllUsers() {
return userData;
}
*/
const resolver = {
Query: {
getAllUsers: ()=> {
return userData;
}
},
};
//console.log(userData);
module.exports = { resolver };

Sequelize umzug migrations Error: Invalid umzug storage

when I am run this code it showing error Invalid umzug storage.
the code are given bellow:
const { Umzug } = require('umzug');
const db = require('../../storage/models');
const umzug = new Umzug({
storage: 'Sequelize',
storageOptions: {
sequelize: db.sequelize, // here should be a sequelize instance, not the Sequelize module
modelName: 'SequelizeMeta',
columnName: 'name'
},
migrations: {
path: '../../storage/models'
},
logger: console,
});
exports.dbmigrate = async (req, res, next) => {
const executed = await umzug.executed();
res.send(executed);
};
Updated Umzug migration tool has some changes in the syntax. I have modified the code you posted. Please try with this code. It should work.
Reference Link: Docs
const {
Umzug,
SequelizeStorage
} = require('umzug');
const db = require('../../storage/models');
const sequelize = db.sequelize;
const umzug = new Umzug({
storage: new SequelizeStorage({ sequelize }),
storageOptions: {
sequelize: db.sequelize, // here should be a sequelize instance, not the Sequelize module
modelName: 'SequelizeMeta',
columnName: 'name'
},
migrations: {
path: '../../storage/models'
},
logger: console,
});
exports.dbmigrate = async (req, res, next) => {
const executed = await umzug.executed();
res.send(executed);
};

Not getting data sent from postman in server.js file from mutation

I am using graphql, prisma & express to test simple query & mutation but when I am sending data from postman I am not getting the data sent from postman,
I am sending this mutation to graphql but inside server.js file
mutation{
createUser(user_name:"test"){
user_name
}
}
, I am getting undefined,
In REST API you can use body parser to fix this for json, Is there anything like same to deal with query & mutaion of graphql with prisma & express
const { PrismaClient } = require('#prisma/client');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { makeExecutableSchema } = require('#graphql-tools/schema');
const prisma = new PrismaClient();
const typeDefs = `
type User {
user_name: String
}
type Query {
allUsers: [User!]!
}
type Mutation {
createUser(user_name:String):User
}
`;
const resolvers = {
Query: {
allUsers: () => {
console.log(prisma)
return prisma.user.findMany();
}
},
Mutation:{
createUser:async(user_name)=>{
console.log(user_name)
user={
"user_name":user_name
}
const test= await prisma.user.create({ data: user })
return test
}
}
};
const schema = makeExecutableSchema({
resolvers,
typeDefs,
});
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
}));
app.listen(5000);
Arguments to your GraphQl query/mutation are passed through the second argument (typically defined as args) of your resolver. Update your Mutation like this
Mutation: {
createUser: async (parent, args, context) => {
console.log(args.user_name);
user = {
user_name: args.user_name,
};
const test = await prisma.user.create({ data: user });
return test;
},
},
I was able to run your code as is after this modification.
I would recommend checking out the documentation for express-graphql or some example code to get more familiar with how the library works. This example is a good place to start how to use express, graphql and prisma. It's in typescript but works very similar to what you need.

profile validation failed: handle: Path `handle` is required

My goal is to build an app that will connect different professionals from different background. I'm also using mongoose as my database.
I created a profile.js that will create and update profiles. But when I test with postman, I get the following error:
"PROFILE VALIDATION FAILED: HANDLE: PATH HANDLE IS REQUIRED."
What can I possibly do to solve this issue?
Your help will be grateful.
const express = require('express'); // require express modules
const router = express.Router(); // to use express router
const auth = require('../../middleware/auth');
const { check, validationResult } = require('express-validator');
const Profile = require('../../models/Profile');
const User = require('../../models/User');
//#route GET api/profile/me
//#desc Get current users profile
//#access Private
router.get('/me', auth, async (req,res) => {
try{
const profile = await Profile.findOne({user: req.user.id}).populate(
'user',
['name', 'avatar']);
if(!profile){
return res.status(400).json({ msg:'No profile exists for this user'});
}
res.json(profile);
} catch(err){
console.error(err.message);
res.status(500).send('Server error');
}
}); //to create a route
//#route POST api/profile
//#desc Create or update users profile
//#access Private
router.post('/',
[
auth,
[
check('status', 'Status is required')
.not()
.isEmpty(),
check('skills', 'Skills is required')
.not()
.isEmpty()
]
] ,
async (req, res) =>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()})
}
const {
company,
website,
location,
bio,
status,
githubusername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin
} =req.body;
//to build profile object
const profileFields = {};
profileFields.user = req.user.id
if(company) profileFields.company = company;
if(website) profileFields.website = website;
if(location) profileFields.location = location;
if(bio) profileFields.bio = bio;
if(status) profileFields.status = status;
if(githubusername) profileFields.githubusername = githubusername;
if(skills){
profileFields.skills = skills.split(',').map(skills => skills.trim());
}
//for the social object
profileFields.social = {}
if(youtube) profileFields.social.youtube = youtube;
if(facebook) profileFields.social.facebook = facebook;
if(twitter) profileFields.social.twitter = twitter;
if(instagram) profileFields.social.instagram = instagram;
if(linkedin) profileFields.social.linkedin = linkedin;
try{
let profile = await Profile.findOne({ user: req.user.id });
if(profile){ //if there is a profile, we will update it
profile = await Profile.findOneAndUpdate(
{ user: req.user.id},
{$set: profileFields },
{new: true}
);
return res.json(profile);
}
//this will create profiles
profile = new Profile(profileFields);
await profile.save();
res.json(profile);
} catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
same code, same issue. In the profile Schema there is a handle field that is set to required. i commented it out and it is working fine now.
the same code you made i made it,you will found handle is required in profile model delete it and your code will working
handle: {
type: String,
required: true,
max: 40
}
Change this code in your models/Profile.js to
handle: {
type: String,
required: false,
max: 40
},
I had the very same Issue . However , it happened because in your "Profile" Schema you probably you made the 'handle' attribute required . So , you must have to give it otherwise just make a change and make the require value to false . Such as (require: false) and hopefully your issue will go .
This is happening because your Profile schema has a handle field(attribute) in which you have a property required: true.
Go to the profile schema file and remove the handle attribute(field) or remove the required: true< from the handle attribute
Example
Profile.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const Profile = new Schema({
...,
handle: {
type: ...,
required: true //remove this line
}
...
});
use
let const profileFields = {};
profileFields.user = req.user.id
that's
let profileFields = {};
profileFields.user = req.user.id
or you can use
const profileFields = {};
profileFields.user = req.user.id;

Create a post route that adds references to its relations

I've got the basic MERN Stack app running I can, GET, POST and Delete Topics and Post separately, they have relationship in Schema but I don't understand how to route it properly to incorporate the relations when POSTing.
const express = require('express');
const router = express.Router();
const Post = require("../../models/Post");
const Topic = require('../../models/Topic');
router.post("/", (req,res) => {
//gets topic id from param
const {topic} = req.params;
//creating a new post
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.body.topic_id
});
//get topic by id
const topic_obj = Topic.findById(topic);
//add posts to topic_object
topic_obj.posts.push(newPost);
//and save
topic_obj.save()
.then(newPost.save()
.then(post => res.json(post)).catch(err => console.log(err)));
});
module.exports = router;
I Don't know if you need more information
I pushed it to GitHub for some helpL https://github.com/wolffles/bloccit-node/blob/react/routes/api/posts.js
Accoarding to TopicSchema:
const TopicSchema = new Schema({
topic: {
type: String,
required: true
},
description: {
type: String,
required: true
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'post'
}
],
date: {
type: Date,
default: Date.now
}});
To incorporate relation between Topic and Post you need to add _id property of newly created Post object to posts field in Topic object that this newly created Post represents.
topic_obj.posts.push(newPost._id);
EDIT:
In your code there are some issues that an cause errors.
const {topic} = req.params; You should validate whether topic is a valid ObjectId
You should also validate request body and check if description and post has required format.
You dupicate Topic id by passing it in request body and also asa request param.
const topic_obj = Topic.findById(topic); This is an async operation, it returns Promise not result of query.
Code should look like (it is not tested):
const express = require("express");
const router = express.Router();
const Post = require("../../models/Post");
const Topic = require("../../models/Topic");
router.post("/:topicId", async (req, res) => {
const { topicId } = req.params;
//TODO: validate if topic is a valid ObjectID
const validTopicId = validateTopicId(topicId);
if (!validTopicId) return res.status(400).send("Invalid param.");
//TODO: validate req.body.description and req.body.post
const validBody = validateBody(req.body);
if (!validBody) return res.status(400).send("Invalid data.");
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: topicId
});
const topic = await Topic.findById(topicId);
if (!topic) return res.status(400).send("Invalid param.");
topic.posts.push(newPost._id);
await topic.save();
await newPost.save();
res.send();
});
module.exports = router;