I'm new in couchbase and I'm using ottoman framework. I connected the database using ottoman and I create the schema and model User and exported it into controller file. When I create a new instance for that model, ottoman throw an error TypeError: User is not a constructor.
I search so many time and I red the official and non official documents and test it severely. I wrote all about the db in separate file and no change. I'll attach the file below it . But I didn't get any solution. please let me know...
const ottoman = require("ottoman");
exports.connect = async () => {
try {
await ottoman.connect({
connectionString: process.env.DB_CONNECTION_STRING,
bucketName: process.env.DB_BUCKET,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
console.log("Database connected.");
await ottoman.start();
} catch (error) {
console.log("Database not connected due to: ", error.message);
}
};
connect();
const User = ottoman.model("User", {
firstName: String,
lastName: String,
email: String,
tagline: String,
});
const perry = new User({
firstName: "Perry",
lastName: "Mason",
email: "perry.mason#example.com",
tagLine: "Who can we get on the case?",
});
const tom = new User({
firstName: "Major",
lastName: "Tom",
email: "major.tom#example.com",
tagLine: "Send me up a drink",
});
main = async () => {
await perry.save();
console.log(`success: user ${perry.firstName} added!`);
await tom.save();
console.log(`success: user ${tom.firstName} added!`);
};
main();
This issue happened due to disorder of functions calling in app.js file. All I used till now was a Mongodb and mongoose in noSQL. In the case of mongodb we can call the database config function after api endpoint specification. I wrote my code like this in couchbase. But it didn't stick in couchbase. I'll provide my code before and after fixing for more clarity, and I'm very sorry for my bad english. :)
Before fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// database setup
const db = require("./config/db");
db.connect();
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
After fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// database setup
const db = require("./config/db");
db.connect();
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
Related
I am working on an educational project from udemy, by dr. yu. I am trying to add content via post request. I keep getting undefined.
From what I can tell, most solutions are user error based with post request and make sure postman form encoded option is checked, or not using body-parser. Both of those seem to be okay on my end.
The code successfully adds content, just, it's empty. Any tips?
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const app = express();
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", { useNewUrlParser: true });
const articleSchema = {
title: String,
content: String,
};
const Article = mongoose.model("Article", articleSchema);
app.get("/articles", function (req, res) {
Article.find(function (err, foundArticles) {
if (!err) {
res.send(foundArticles);
} else {
res.send(err);
}
});
});
app.post("/articles", function (req, res) {
const newArticle = new Article({
title: req.body.title,
content: req.body.content,
});
newArticle.save(function (err) {
if (!err) {
res.send("Successfully added a new article.");
} else {
res.send(err);
}
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function () {
console.log(`Server started on port ${port} successfully`);
});
Im learning node js and MongoDB through a tutorial. Im creating a CRUD.
The connection with MongoDB is successful, but it shows this error: TypeError: Tutorial is not a constructor.
models/tutorial.model.js
const mongoose = require("mongoose");
const Tutorial = new mongoose.Schema({
title: String,
description: String,
published: Boolean
})
module.exports = mongoose.model("tutorial", Tutorial)
server.js
const express = require("express");
const bodyParser = require("body-parser")
const cors = require("cors")
const app = express();
const connectDB = require("./config/db")
var corsOptions = {
origin: "http://localhost:8081"
}
//connnect the database
if(connectDB()){
console.log("connected")
}
app.use(cors(corsOptions))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get("/", (req, res) => {
res.json({ message: "Welcome to application" })
})
//setting the port
require("./routes/tutorial.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
controller/tutorial.controller.js
const db = require("../models")
const Tutorial = db.tutorials
//create and save
exports.create = (req, res) => {
//validate request
if(!req.body.title) {
res.status(400).send({message: "Content cannot be empty"})
}
const tutorial = new Tutorial({
title: req.body.title,
description: req.body.description,
published: req.body.published ? req.body.published : false
})
tutorial
.save(tutorial)
.then(data => {
res.send(data)
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occured while creating the Tutorial"
})
})
}
How can I solve this error?
When you require a directory, node looks for the index.js file inside the directory.
This line:
const db = require("../models")
is loading your empty models/index.js file (could also be models.js but I would advise sticking with the index.js file as that's the standard)
This file should load all models and export them as an object:
module.exports = {
tutorial: require("./tutorial")
}
Which will allow you to use:
const db = require("../models")
const Tutorial = db.tutorial
note I dropped the s after db.tutorial to stay consistent and avoid typos.
im trying to put together a simple website, but when trying to insert to my Heroku database it says my relation (table) does not exist but in fact exists!!..I connect through database_url provided by Heroku and when I connect through my command line and insert new rows, they get added and I can see their table and data but when I try to insert the data everytime I hit summit in the form, the error pops up like there were no table with that name..
const express = require('express');
app = express();
require('dotenv').config()
var sslRedirect = require("heroku-ssl-redirect").default;
var compression = require('compression');
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
})
//MIDDLEWARE
app.set("port",process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(sslRedirect());
app.disable('x-powered-by');
app.use(compression());
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended:false
})
);
app.use
const errorController = require('./controllers/errorController');
//const middleware = require('./controllers/middleware')
//ROUTES
app.get('/',(req,res,next) => {
res.render('test')
});
app.post('/thanks', async (req, res) => {
data = {
name : req.body.name,
email : req.body.email,
service: req.body.service,
message: req.body.message};
const text ='INSERT INTO customers(name,email,service,message) VALUES($1, 2$, 3$, 4$) RETURNING *;'
const values = [data.name, data.email, data.service, data.message];
client.connect()
try {
const res = await client.query(`INSERT INTO customers (name,email,service,message) VALUES(${data.name},${data.email},${data.service},${data.message}) RETURNING *;`);
console.log(res.row[1])
client.end()
}catch (err) {
console.log(err.stack)
client.end()
}
res.render('thanks')
})
app.get('/contact',(req,res) => {
res.render('contact')
})
app.get("/services" , (req,res) => {
res.render('services')
})
app.get("/about" , (req,res) => {
res.render("about")
})
app.get('/maysspabeauty.com/contact/*' , (req , res) => {
res.render('contact')
})
app.use(errorController.pageNotFoundError);
app.use(errorController.internalServerError)
app.listen(app.get("port"), () => {
console.log(`server running at http://localhost:${app.get("port")}`);
});
here is screenshot of the errorerror image
Solved this.... seems my problem was just that i was using heroku hobby-dynos and they are NOT meant to be used in production....after i upgraded the dynos, it just throw me this error (no pg_hba.conf entry for host) which i fixed just using ssl"{
ssl:
rejectUnauthorized:false
};
I'm going to develop API using Node Express & Mongo.I have manually entered data to mongo db like below and when i try to get data from the db it shows me empty in postman.Here i have paste my project code for easy to figure out.
In the controller returned empty results.
my project structure looks like this
db.config.json
module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
};
server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Shopping List." });
});
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;
user.contoller.js
const db = require("../models");
const User = db.users;
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
User.find({ isAdmin: false })
.then(data => {
console.log("datanew"+data); // <-- Empty returns here.. []
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving user."
});
});
};
user.model.js
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("user", schema);
return User;
};
user.route.js
module.exports = app => {
const users = require("../controllers/user.controller.js");
var router = require("express").Router();
// Retrieve all Tutorials
router.get("/", users.findAll);
app.use('/api/users', router);
};
It appears you manually created your MongoDB collection. Users must be in small letters so from the MongoDB interface, change Users => users and you'll be set.
Also your DB connection uri should be:
module.exports = {
url: "mongodb://localhost:27017/TestDb"
};
TestDB is the database while users is the collection. Your uri must point to a db that your code will query collections in.
Your User Model
This is just a slight change but you want to keep your code consistent. User should all be in capitalize form. MongoDB is smart to user plural and small caps automatically in the db.
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("User", schema);
return User;
};
// Actually you can remove
index.js
db.config.js files
// *********
add in server.js
const express = require('express')
const mongoose = require('monggose')
const app = express()
mongoose.connect('mongodb://localhost/TestDb');
I have tried to post in MongoDB by using postman while posting a text i got a error of (Couldnt get any Response) It is not showing any error to Command nodemon Please help me where i did mistake ..! what i need to do ?
My index.js file is:-
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./configdb/database');
// Connection to database
mongoose.connect(config.database);
// Connection Success to DB
mongoose.connection.on('connected',() => {
console.log('Connected to the Database ' +config.database);
});
//on Error while Connecting
mongoose.connection.on('error',(err) => {
console.log('connection ERROR Try Again Database Failed to Connect ' +err);
});
const app = express();
const articles = require('./routers/articles');
// Port to start
const port = 2200;
// cors middleware
app.use(cors());
// Set Static Public folder
app.use(express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/articles',articles);
// Index Route
app.get('/', (req, res) => {
res.send('this is initial page for starting all session')
});
app.listen(port, () => {
console.log('server started in' + port)
})
my articles.js file is
const express = require('express');
const router = express.Router();
const config = require('../configdb/database');
const Article = require('../models/article');
// Register of article
router.post('/new-article', (req,res,next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
return;
article.save(function(err){
if(err){
res.json({success: false, msg: 'Failed to Register the Article' });
} else {
res.json({success: true, msg: 'New Article is Registered'});
}
});
});
module.exports = router;
my article.js file is
const mongoose = require('mongoose');
const config = require('../configdb/database');
const ArticleSchema = mongoose.Schema({
title:{
type: String,
}
});
const Article = module.exports = mongoose.model('Article', ArticleSchema)
But I have got the message from
article.title = req.body.title; and my error as follows:-
In articles.js you have return the function after displaying title cause the problem!
// Register of article
router.post('/new-article', (req, res, next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
// return;
article.save(function (err) {
if (err) {
res.json({
success: false,
msg: 'Failed to Register the Article'
});
} else {
res.json({
success: true,
msg: 'New Article is Registered'
});
}
});
});