OverwriteModelError: Cannot overwrite `teams` model once compiled - javascript

After several hours. Research in StackOverflow. There are a lot of articles about this issue. But I can't figure out what I'm wrong here.
My code:
models/Team.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const teamSchema = new Schema({
name: { type: String, minLength: 1, required: true },
description: { type: String },
});
mongoose.model('teams', teamSchema);
models/Division.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const divisionSchema = new Schema({
name: { type: String, minLength: 1, required: true },
description: { type: String },
});
mongoose.model('teams', divisionSchema);
And I was required in index.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./config/keys');
require('./models/Team');
require('./models/Division');
mongoose.Promise = global.Promise;
mongoose.connect(keys.mongoURI, { useNewUrlParser: true });
const app = express();
app.use(bodyParser.json());
require('./routes/teamRoutes')(app);
const port = process.env.PORT || 5000;
app.listen(port);
routes/teamRoutes.js
const mongoose = require('mongoose');
const Team = mongoose.model('teams');
module.exports = (app) => {
app.get('/api/teams', async (req, res) => {
const teamsList = await Team.find({});
res.send(teamsList);
});
};
If I delete require('./models/Division');, It works. Why is that?
If not, I got the error:
throw new mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `teams` model once compiled.

mongoose.model('teams', divisionSchema);
'teams' should be 'division' in models/Division.js I guess

Related

Problem during uploading data to MongoDB (node.js)

When I'm uploading data about my new user I don't get any information back with the new json file where is saved my user, I only get '{}' and that's all. I'm sending here my code and what I get in Postman.
index.js
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const mongoose = require('mongoose');
const { CLIENT_RENEG_LIMIT } = require('tls');
const { application } = require('express');
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('Connected to Mongoose server'))
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use('/api/users', userRoute);
app.use('/api/auth', authRoute);
app.listen(process.env.PORT || 5200, ()=>{
console.log('Listening on port 5200');
});
auth.js
const router = require('express').Router();
const user = require('../models/user');
//REJESTRACJA
router.post('/rejestracja', async (req, res)=>{
const newUser = new user({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const saveduser = newUser.save();
res.status(201).json(saveduser);
}catch(err){
res.status(500).json(err);
}
});
module.exports = router
user.js
const mongoose = require('mongoose');
const {Boolean} = require('webidl-conversions');
const UserSchema = new mongoose.Schema({
username: { type: 'string', unique: true, required: true},
email: { type: 'string', unique: true, required: true},
password: { type: 'string', required: true, unique: true},
admin: { type: 'Boolean', default: false},},
{timestamps: true}
)
module.exports = mongoose.model('User', UserSchema);
postman screenshot

Unable to access object properties while doing a post request

I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.

Node JS Type Error : Cannot read property

I am a beginner nodejs developer, and for a start I decided to develop a blog project for practice. I am using Nodejs Express and native js on the client. When adding a post, nodejs throws an error in the routes:
(node: 25967) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'title' of undefined
at router.post (/routes/post.js:15:25)
Here is my code:
routes/post.js
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
// http://localhost:5000/api/post (GET)
router.get('/', async (req, res) => {
const posts = await Post.find({})
res.status(200).json(posts)
})
// http://localhost:5000/api/post (POST)
router.post('/', async (req, res) => {
const postData = {
title: req.body.title,
text: req.body.text
}
const post = new Post(postData)
await post.save()
res.status(201).json(post)
})
// http://localhost:5000/api/post/id (DELETE)
router.delete('/:postId', async (req, res) => {
await Post.remove({_id: req.params.PostId})
res.status(200).json({
message: 'Deleted'
})
})
module.exports = router
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const postRouter = require('./routes/post');
const keys = require("./keys");
const port = process.env.PORT || 5000;
const clientPath = path.join(__dirname, 'client');
const app = express();
app.use(express.static(clientPath))
app.use('/api/post', postRouter)
app.use(bodyParser.json())
mongoose.connect(keys.mongoURI, { useNewUrlParser: true,
useUnifiedTopology: true, useCreateIndex: true })
.then(() => console.log('MongoDB connected'))
.catch( err => console.error(err));
app.listen(port, () => {
console.log(`Server has been started on port ${port}`);
});
(model)Post.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema ({
title: {
type: String,
required: true,
},
text: {
type: String,
required: true
},
date : {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('posts', postSchema)
what could be the problem?
This is an ordering problem, switch these lines around:
app.use('/api/post', postRouter)
app.use(bodyParser.json())
Express middlewere are run in order, which in your case means your post route will be called before the bodyParser middleware is able to parse the JSON body.

Why I'm getting the error "Must provide query string." express-graphql?

I'm beginning with graphql on express. I'm getting the error "Must provide query string." when I access to the route for it.
It's an express app. Here is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
let bodyParser = require('body-parser');
var cors = require('cors');
const graphqlHTTP = require('express-graphql');
const MySchema = require('./schema/schema');
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/graphql', graphqlHTTP({
schema: MySchema,
graphiql: true,
}));
And my shema is:
const graphql = require('graphql');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLList
} = graphql;
//MODELS FROM MONGOOSE
const Entidad = require('../models/entidad');
//TYPES GRAPHQL
const EntidadType = new GraphQLObjectType({
name: 'Entidad',
fields : () => ({
id : {type : GraphQLString},
nombre : {type : GraphQLString},
created_at : { type : GraphQLString},
updated_at : { type : GraphQLString},
})
});
//ROOT QUERY
const RootQuery = new GraphQLObjectType({
name : 'RootQueryType',
fields : {
entidad : {
type: EntidadType,
args: {id:{type: GraphQLString}},
resolve(parent, args){
//code to get data from db
return Entidad.findById(args.id);
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
I don't know why I'm getting the error when open graphiql.
I test other examples and give me the same error, maybe there is some part that I missed....
Some idea?
Well, I commented the line of body-parser and I fix the problem, the other problem is because I don't have a rootValue into the route of graphql. I tested the queries and it's all ok. Thanks.

Mocha test successfully connecting to my database but not saving instances

src/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const UserSchema = new Schema({
name : String
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
test/test_helper.js
// DO SOME INITIAL SETUP FOR TEST
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useMongoClient : true });
mongoose.Promise = global.Promise;
mongoose.connection
.once('open', ()=> console.log('Good to go'))
.on('error',(error)=> {
console.warn('Warning',error);
});
test/create_test.js
const assert = require('assert');
const User = require('../src/user');
const mongoose = require('mongoose');
describe('Creating records', () => {
it('saves a user', () => {
const joe = new User({ name : 'Joe' });
joe.save();
});
});
When I am trying to save the instance in the create_test.js , its not saving it in the database. But when I save an instance in the file test_helper.js , it is working . Any suggestions?
It's because mongoose opens connection after that the test is running. You need to use before hook to guarantee that connection is opened.
before(done => {
mongoose.connect('mongodb://localhost/test', { useMongoClient : true });
mongoose.Promise = global.Promise;
mongoose.connection
.once('open', () => done())
.on('error', err => console.err('Db connection error', err);
});
});

Categories