I'm trying to use a very basic MongoDB method is to save a document on a database with mongoose.
1.I installed my MongoDB in centos 7
2.Create a database on the Mongo shell using: use mydatabase and insert a document inside it as normal.
3.Install mongoose and make a connection between my nodejs app and the MongoDB:
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
4. test the connection and all is fine with:
db.once('open', () => {
console.log('DB Connected');
});
Import the model schema as normal:
var { Classe } = require('../DBModels/GoClassDBModels/classes');
try to add new document like this:
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
newClasse.save()
My Model is:
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model('Classes', classSchema);
module.exports = { Classe };
SERVER.JS:
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cookieParser = require('cookie-parser');
const _ = require('lodash');
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log('server is started on 80');
});
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once('open', () => {
console.log('DB Connected');
});
db.on('error', (err) => {
console.log(err);
});
var { Classe } = require('../DBModels/GoClassDBModels/classes');
const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(['lakkini.com']));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
next();
});
app.set('view engine', 'hbs');
app.use(express.static('/home/admin/SMS'));
app.use(express.static('/home/admin/assets'));
app.get('/', (req, res) => {
res.render('SMS/dashboard.hbs');
});
app.get('/classes', (req, res) => {
res.render('SMS/classes.hbs');
});
app.get('/inscription', (req, res) => {
res.render('SMS/inscriptions.hbs');
});
app.post('/saveClasse', (req, res) => {
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
console.log('im gonna save the new class');
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log(response);
});
});
The problem is: nothing happened. No document has been inserted and no errors.
Can you suggest to me, please ?
PS: I'm trying to request from an HTTP server without HTTPS.
will that affect my requests nd block the save to the database?
result:
click to see the picture of the result please
Since the whole file was not given for mongoose connection and where save function is called , assuming you have structured it properly i'm giving my answer.
I was able to do this way,
The schema (same as yours) :
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model("Classes", classSchema);
module.exports = { Classe };
Function to insert:
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("DB Connected");
var newClasse = new Classe({
label: "hello",
level: "level",
});
newClasse.save();
});
UPDATE:
SERVER.JS
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cookieParser = require("cookie-parser");
const _ = require("lodash");
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log("server is started on 80");
});
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once("open", () => {
console.log("DB Connected");
});
db.on("error", (err) => {
console.log(err);
});
var { Classe } = require("./models/Classe");
// const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(["lakkini.com"]));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
"Cache-Control",
"no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"
);
next();
});
app.set("view engine", "hbs");
// app.use(express.static("/home/admin/SMS"));
// app.use(express.static("/home/admin/assets"));
// app.get('/', (req, res) => {
// res.render('SMS/dashboard.hbs');
// });
// app.get('/classes', (req, res) => {
// res.render('SMS/classes.hbs');
// });
// app.get('/inscription', (req, res) => {
// res.render('SMS/inscriptions.hbs');
// });
app.post("/saveClasse", (req, res) => {
var newClasse = new Classe({
label: "hello",
level: "level",
});
console.log("im gonna save the new class");
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log("RESPONSE" + response);
});
});
I found the issue, but I don't understand why that.
the first structure was:
**
DBModel
classes.js
Server
server.js**
the structure right now:
**
DBModel
classes.js
server.js
**
I make out the server from that folder and all working fine...??
why that?
Related
Mongo save callback is not triggering, but the document is getting saved in the db, Heres my code:
MongoDb Version : 6.0.1
Mongoose Version : 6.8.2
The call back not returning anything, but the documents are getting saved without any issues, why the call back is not triggering?
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const url = 'mongodb://127.0.0.1:27017/musicapp';
const cors = require('cors');
var jquery = require('jquery');
//Mongodb
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set('strictQuery', true);
var conn = mongoose.connection;
conn.on('connected', function () {
console.log("Database Connected");
})
var artistSchema = new mongoose.Schema({
artistName: String,
artistDob: String,
artistBio: String
})
const artists = mongoose.model("artist", artistSchema);
function addArtist(aName, aDOB, aBIO) {
const newArtist = new artists({
artistName: aName,
artistDob: aDOB,
artistBio: aBIO
})
newArtist.save((err, data, numAffected) => {
if (!err) {
return true;
}
else {
return false;
}
});
}
//MongoDb
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
})
app.post("/addsongs", cors(), (req, res) => {
console.log("Add songs");
})
app.post("/addartist", cors(), (req, res) => {
var artistName = req.body.modalartistname;
var artistDOB = req.body.modalartistdob;
var artistBio = req.body.modalartistbio;
var addedArtist = addArtist(artistName, artistDOB, artistBio);
if (addedArtist) {
res.sendStatus(200);
}
else {
console.log("Failure")
res.sendStatus(400);
}
//console.log("Artist Added Sucessfully");
})
app.listen(3000, function () {
console.log("The Server is up and running");
})
I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {
I tried to make a MEAN stack app, but my API fails to give my requested data.
server.js file:
const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;
//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');
mongoose.Promise = global.Promise;
mongoose.connect(
dburi,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
).then(
() => {
console.log('Connected to mongoDB');
},
(err) => console.log('Error connecting to mongoDB', err),
{ useNewUrlParser: true }
);
//Express app
const app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
console.log(`running at port ${port}`);
});
Routes file:
const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();
router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);
module.exports = router;
Controller file:
const VolcanoSchema = require('../models/volcano.models');
const getAllVulcanoes = (req, res) => {
VolcanoSchema.find((err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVolcanoes};
Model file
const mongoose = require('mongoose');
const VolcanoSchema = new mongoose.Schema({
Volcano_name:{
type: String,
},
Country:{
type: String,
},
Type:{
type: String,
},
Latitude:{
type: Number,
},
Longtitude:{
type: Number,
},
Elevation:{
type: Number,
},
});
module.exports = mongoose.model('Volcano', VolcanoSchema);
The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this
It would be nice if someone point out what i am doing wrong
EDIT: I switched to postgresql for my database hopefully this will work
You should fix the Controller (VulcanoSchema.find needs an empty object as parameter):
Controller file:
const VulcanoSchema = require('../models/vulcano.models');
const getAllVulcanoes = (req, res) => {
VulcanoSchema.find({}, (err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVulcanoes};
This is indeed a duplicate question however there is no answer.
The problem is that when I save a new record with mongoose through a post request, all that's saved is something like this:
{ "_id" : ObjectId("5d11590975c82f216eaa4712"), "__v" : 0 }
I am following this tutorial so the code should work fine, but regardless here it is:
the mongoose schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
}
});
module.exports = mongoose.model('Todo', Todo);
the code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
todoRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Todo.findById(id, function(err, todo) {
res.json(todo);
});
});
todoRoutes.route('/update/:id').post(function(req, res) {
Todo.findById(req.params.id, function(err, todo) {
if (!todo)
res.status(404).send("data is not found");
else
todo.todo_description = req.body.todo_description;
todo.todo_responsible = req.body.todo_responsible;
todo.todo_priority = req.body.todo_priority;
todo.todo_completed = req.body.todo_completed;
todo.save().then(todo => {
res.json('Todo updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
todoRoutes.route('/add').post(function(req, res) {
let todo = new Todo(req.body);
todo.save()
.then(todo => {
res.status(200).json({'todo': 'todo added successfully'});
})
.catch(err => {
res.status(400).send('adding new todo failed');
});
});
app.use('/todos', todoRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
the post request:
the get request:
To confirm here's the output in mongodb:
the problem is that the body needs to be Json(application/json) instead of Text
Everything is fine with your code
Just add this line to your todo.model.js
module.exports = mongoose.model('Todo', Todo);
1:
Edit:
I also had this problem and I fixed Content-type: application / json and it worked
make sure you added app.use(express.json()) to your server.js file.
Try using body-parser and use:
app.use(bodyParser.json());
In the app.js file
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!