I am a frontend developer. A colleague has kindly built me a MongoDB/Cosmos database in Azure and allowed me to retrieve a single record into my frontend. He has since gone on holiday with no cover.
(I am confused what type of database it is, since it says Azure Cosmos DB in Azure portal, but all the code in my server.js file refers to a MongoDB.) Server.js:
const express = require('express');
const app = express();
const url = 'mongodb://blah.azure.com';
app.use(express.static('static'));
const mongoClient = require('mongodb').MongoClient
let db;
app.listen(process.env.PORT || 3000, async () => {
console.log('App listening on port 3000!')
const connect = await mongoClient.connect(url)
db = connect.db('ideas');
});
app.get('/api/ideas/:name', async (req, res) => {
return res.json(await db.collection('container1').findOne({key: req.params.name}));
});
I want to retrieve all documents in this database. They each have an ID. But my colleague seems to have defined an API by name. From the MongoDB docs I can use the command find({}) instead of findOne({key: req.params.name}) to return all records, but this does not work (i.e. I get no output to the console). I presume this is because of the '/api/ideas/:name'.
I have also tried:
db.open(function(err, db){
var collection = db.collection("container1");
collection.find().toArray(function(err2, docs){
console.log('retrieved:');
console.log(docs);
})
})
but i get an error that tells me I can't retrieve the property "open" of undefined.
Can anyone help me either: (1) work out how to change the API in Azure, or (2) rewrite this code to retrieve all records? I will also need to edit and insert records. Thanks
If you want to retrive data from Mongo DB in nodejs espresso application, I suggest you use the package mongoose.
For example
Create mongo.js file to add connection details
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const accountName= 'testmongo05',
const databaseName= 'test',
const key= encodeURIComponent(''),
const port: 10255
const mongoUri = `mongodb://${env.accountName}:${key}#${accountName}.documents.azure.com:${port}/${databaseName}?ssl=true`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, {
useFindAndModify : false,
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = {
connect,
mongoose
};
Define models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
userId: {
type: String,
required: true,
unique: true
},
name: String,
saying: String
},
{
collection: 'Users'
}
);
const User = mongoose.model('User', userSchema);
module.exports = User;
CURD operations
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./module/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
require('./mongo').connect().catch(error => console.log(error));
//list users
app.get('api/users', async (req, res) => {
const docquery = User.find({});
await docquery
.exec()
.then(users => {
res.status(200).json(users);
})
.catch(error => {
res.status(500).send(error);
});
});
// get user by userId
app.get('/api/user/:uid', async (req, res) => {
const docquery =User.findOne({userId:req.params.uid })
await docquery
.exec()
.then(user => {
if (!checkFound(res, user)) return;
res.status(200).json(user);
})
.catch(error => {
res.status(500).send(error);
});
});
// create
app.post('/api/user', async (req, res) => {
const originalUser= { userId: req.body.userId, name: req.body.name, saying: req.body.saying };
const user = new User(originalUser);
await user.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json('User created successfully!');
console.log('User created successfully!');
});
});
//update user by userId
app.put('/api/user/:uid', async (req, res) => {
const docquery =User.findOneAndUpdate({userId: req.params.uid}, req.body)
await docquery.exec()
.then((user) =>{
if (!checkFound(res, user)) return;
res.status(200).json("User update successfully");
console.log('User update successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
//delete user by userId
app.delete('/api/user/:uid', async (req, res) => {
const docquery = User.findOneAndRemove({userId: req.params.uid })
await docquery.exec()
.then(user =>{
if (!checkFound(res, user)) return;
res.status(200).json("user deleted successfully!");
console.log('user deleted successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function checkFound(res, user) {
if (!user) {
res.status(404).send('user not found.');
return;
}
return user;
}
Test
a. Create user
b. get user
c. List Users
d. Update User
e delete user
Related
Been following trying to get a mongoose server setup, and it briefly worked, but now it's not for some reason and I honestly have no idea what's going on. No matter what I do, it's returning a blank []?
Collection is "users" all lowercase. Config is in other files. Like I said it has worked before for me briefly and I have no clue why it suddenly stopped.
EDIT - The user object is undefined so it's not even pulling the data from the db for some reason?
server.js
const express = require('express')
const cors = require('cors')
const app = express()
var corsOptions = {
origin: "http://localhost:8080"
}
app.use(cors(corsOptions))
app.use(express.json())
app.use(express.urlencoded({extended:true}))
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();
});
app.get("/", (req, res) => {
res.json({ message: "Welcome to server." });
});
require("./app/routes/user.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
model
module.exports = mongoose => {
var schema = mongoose.Schema(
{
id: Number,
ref: String,
name: String,
achieves: Array,
total: Number
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("users", schema);
return User;
};
findAll method in controller
exports.findAll = (req, res) => {
const name = req.query.name;
var condition = name ? { name: { $regex: new RegExp(name), $options: "i" } } : {};
User.find(condition)
.then(data => {
res.send(data);
console.log(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users."
});
});
};
Try this one at query:
{name: {$regex : `.*${name}.*`, $options: "i"}}
i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());
I made an application to make push notifications and I succeeded in sending notifications. But I have a problem, which is that I want to save any notification that I send in my database,
Here is the code,
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.post("/fcm", async (req, res, next) => {
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, function (err, response) {
if (err) {
next(err);
} else {
// res.json(response);
// res.send(message.notification.body);
app.post("/notfs", async (req, res) => {
let newNotf = new NotificationModel({
name: message.notification.body,
});
newNotf = await newNotf.save();
res.send(newNotf);
});
}
});
} catch (error) {
next(error);
}
});
app.get("/notfs", async (req, res) => {
const notfs = await NotificationModel.find();
res.send(notfs);
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
Why doesn't it save notifications in the database?
Another question
Please if there is a better way than this please leave it and thank you٫
Thanks in advance
use axios package, which is recommended by nodejs official.
Its simple like jquery ajax call
So I'm trying to set this form page, the information is being sent but the database is not being created automatically, and consequently, my info is not being saved
Sorry for the long post and thanks for any feedback
This is my app.js
mongoose.connect('mongodb://localhost/cloud', {
useNewUrlParser: true
})
})
.catch(err => console.log(err));
require('./models/post');
const post = mongoose.model('post');
const app = express();
app.post('/cloud', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.render('index', {
msg: err
});
} else {
console.log(req.body);
const newUser = {
title: req.body.title,
}
new post(newUser).save().catch(post => {
res.redirect('/cloud');
})
}
});
});
app.get('/cloud', (req, res) => {
post.find({})
.sort({Date: 'desc'})
.then(posts => {
res.render('cloud/cloud', {
posts: posts
});
});
});
const port = 3000;
app.listen(port, () => {
console.log(`running ${port}`);
});
Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema ({
title:{
type: String,
required: true
}
});
mongoose.model('post', postSchema);
Handlebars file
{{#each posts}}
<h4>{{title}}</h4>
{{else}}
<p>No pics found</p>
{{/each}}
You did not specify your schema property at this line of your code.
new post(newUser).save().catch(post => {
res.redirect('/cloud');
The correct way is
new post({title: new User} ).save().catch(post => {
res.redirect('/cloud');
Now, you have specify mongoose to save a new record for title.
I am trying to make a post request to the server (mongodb) but I get this error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
I am running mongodb on my localhost
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.get("/:id", async (req, res) => {
try {
const id = req.params.id;
await Todo.findById(id, (err, todo) => {
res.json(todo);
});
} catch (err) {
res.json({ message: err });
}
});
router.post("/add", async (req, res) => {
const todo = new Todo({
todo_description: req.body.todo_description,
todo_responsible: req.body.todo_responsible,
todo_priority: req.body.todo_priority,
todo_completed: req.body.todo_completed,
});
try {
await todo.save();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.patch("/update/:id", async (req, res) => {
try {
const updateTodo = await Todo.updateOne(
{ _id: req.params.id },
{ $set: { todo_description: req.body.todo_description } }
);
updateTodo.save().then(updateTodo => {
res.json(updateTodo);
});
} catch (err) {
res.json({ message: err });
}
});
router.delete("/delete/:id", async (req, res) => {
try {
const deleteTodo = await Todo.deleteOne({ _id: req.params.id });
res.json(deleteTodo);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
my todo model
// Require Mongoose
const mongoose = require("mongoose");
// Define Schema
// const Schema = new mongoose.Schema;
// Define Todo-Schema
const TodoSchema = new mongoose.Schema({
// Creating Fields
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
},
todo_date: {
type: Date,
default: Date.now
}
});
// Compile Model From Schema
// const TodoModel = mongoose.model("Todos", TodoSchema);
// Export Model
module.exports = mongoose.model("todos", TodoSchema);
error message:
(node:548) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
at router.post (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\routes\todo.js:33:32)
at Layer.handle [as handle_request] (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\node_modules\express\lib\router\layer.js:95:5)
thank you
You are accessing todo_description from req.body. req.body will only be available if you add the body-parser middleware or add a similar one yourself.
Add this right before your routes are loaded :
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
You can also add this to a specific route. Read more about it here.
You should use body-parser in your master file of the application. Which gives you the parsed json before your middle-ware parse the body, which by-default in string. And also make sure you are sending todo_description in the req.body(should check before use).
const bodyParser = require('body-parser');
app.use(bodyParser.json());