Mocha test successfully connecting to my database but not saving instances - javascript

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);
});
});

Related

Getting TypeError: User is not a constructor when testing user add with API

I am trying to make my backend work with MongoDB ATLAS.
I'm using express, mongoose and node.js for my tests and when I am trying to test my API routes (in this case to add a user)
The code I have is the following:
users.js
const router = require('express').Router();
const { Router } = require('express');
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router
user.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
When I am testing this with postman via a POST I get the following error: I am getting the following error: TypeError: User is not a constructor
The post is done to http over port 5000 with raw json body as "username": "blahblahblah"
Can you help with this maybe?
I am not sure what happened but today I cut and pasted back all the code and the API started to work just fine. Now I can add users without any problems.
Could be a glitch but not sure at this point.

Mongoose .find is not a function?

I am using mongoose version ^5.10.2 and I've been able to save data to the mongo Atlas database BUT I can not get the data down. When I try using:
const mongoose = require('mongoose');
const express = require('express');
{
const config = require("./config.json")
var token = config.token;
var prefix = config.prefix;
var botName = config.botName;
}
const server = require('./server.js');
server();
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
modName: String,
modUrl: String
});
// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema);
setInterval(function () {
// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ 'ModName': 'Kiddions mod menu', 'modUrl': 'https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946' });
console.log('---Direct info---');
console.log('Name: ' + awesome_instance.ModName);
console.log('URL: ' + awesome_instance.modUrl);
// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
if (err) return handleError(err);
// saved!
});
awesome_instance.find({}, function(err, data){
console.log(">>>> " + data );
});
}, 2000);
Server.js code:
const express = require('express');
const connectDB = require('./DB/Conncection');
const app = express();
module.exports = function server() {
connectDB();
app.use(express.json({ extended: false }));
app.use('/api/userModel', require('./Api/Mod'));
const Port = process.env.Port || 3030;
app.listen(Port, () => {
console.log('Server started')
});
}
Connection.js code:
const mongoose = require('mongoose');
const URI =My database";
const connectDB = async () => {
await mongoose.connect(URI, {
useUnifiedTopology: true,
useNewUrlParser: true
});
console.log('DB connected..!');
};
module.exports = connectDB;
It fails... I get the bug:
Server started
DB connected..!
---Direct info---
Name: undefined
URL: https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946
C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45
**awesome_instance.find({}, function(err, data){
^
TypeError: awesome_instance.find is not a function
at Timeout._onTimeout (C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45:22)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
I have used this as a function for a while but it stopped working recently. Could it be because I updated mongoose?
awesome_instance is a document .find is a method present in collection/models so try
SomeModel.find({}, function(err, data){
console.log(">>>> " + data );
});

Save data to MongoDB using NodeJS

I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")

Send Arraydata from the from react to node. and save it in mongoose

I am trying to send an array from react using axios to my Node.js file, however I am getting an status 404 error.
My profileSchema as follows:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
preference: [
{
type: String
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
I want to send an array to the back end with an axios request.
for example
tempArray=["Chocoloate","Vanilla","Strawberry"]
and the axios request I make is
axios
.post('/api/profile/register', tempArray)
.then(res => console.log(res.data))
.catch(err => console.log(err));
My profile.js look list this. I also have body-parse and all installed.
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const passport = require("passport");
const Profile = require("../../models/Profile");
// Load User Model
const User = require("../../models/User");
router.get("/test", (req, res) => res.json({ msg: "Profile Works" }));
// #route POST api/profile
// #desc Create or edit user profile
// #access Private
router.post(
"/register",
(req, res) => {
console.log(req);
var list = req.body;
console.log(list);
}
);
However, I am still getting 404 errors and not being able to save the array to the backend
index.js file
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const posts = require("./routes/api/posts");
const issues = require("./routes/api/issues");
const mp = require("./routes/api/mp");
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport Config
require("./config/passport")(passport);
// Use Routes
app.use("/api/users", users);
app.use('/api/profile', profile);
app.use("/api/posts", posts);
app.use("/api/issues", issues);
app.use("/api/mp", mp);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
Always try sending the post body as an object.
tempArray = ['a', 'b', 'c']
axios
.post('/api/profile/register', {tempArray: tempArray})
.then(res => console.log(res.data))
.catch(err => console.log(err));
and the body params in the router.post as
router.post('/register/', function(req, res,next) {
const tempArray = req.body.tempArray;
//perform your query operations here and pass tempArray as params to your query
})

OverwriteModelError: Cannot overwrite `teams` model once compiled

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

Categories