How to get data in Angular 2 service with Mlab - javascript

import { Injectable } from '#angular/core';
#Injectable()
export class UserService {
constructor() {
console.log("Users service initialized");
}
getUsers(){
//Mlab URL
//Example: mongodb://user:password#ds129038.mlab.com:29038/database_name
}
}
Hi, i'm looking the way to get users in angular 2 service from a database in MLAB. How could I receive them and iterate results?
Regards,

In your app folder make a new folder and name it "server"
Inside "server" folder make two new folders and name the "models", and "routes"
In models folder create a javascript file and name it same as your collection name in mlab/mongodb. Example "datacollection1.js"
Inside datacollection1.js paste the following code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const datacollection1Schema = new Schema({
varone: String,
vartwo: String,
varthree: String,
varfour: String
});
module.exports = mongoose.model('datacollection1', herodataSchema, 'datacollection1class');
Inside "routes" folder create a file and name it "api.js"
Paste the following code in api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Datacollection1class = require('../models/datacollection1');
const db = "mongodb://:#ds155201.mlab.com:<12345>/";
mongoose.Promise = global.Promise;
mongoose.connect(db, function(err){
if(err) {
console.log("Error: " + err);
}
});
//Get all data
router.get('/datacollection1class', function(req, res) {
console.log("Get request for datacollection1class");
Datacollection1class.find({})
.exec(function(err, datacollection1class){
if(err) {
console.log("Error retrieving datacollection1class.");
} else {
res.json(datacollection1class);
}
})
});
//retrieve data by id
router.get('/datacollection1class/:id', function(req, res) {
console.log("Get request for sigle document");
Datacollection1class.findById(req.params.id)
.exec(function(err, datacollection1classsingle){
if(err) {
console.log("Error retrieving datacollection1classsingle.");
}
else
{
res.json(datacollection1classsingle);
}
})
});
//Add a single new documemt
router.post('/datacollection1classsingle', function(req, res){
console.log('Post a data set');
var newDatacollection1classsingle = new Datacollection1class();
newDatacollection1classsingle.varone = req.body.varone;
newDatacollection1classsingle.vartwo = req.body.vartwo;
newDatacollection1classsingle.varthree = req.body.varthree;
newDatacollection1classsingle.varfour = req.body.varfour;
newDatacollection1classsingle.save(function(err, insertedDatacollection1classsingle){
if (err) {
console.log('Error saving new hero data: '+err);
} else {
res.json(insertedDatacollection1classsingle);
}
});
});
//Update existing document
router.put('/hatacollection1class/:id', function(req, res) {
console.log('Update a video');
Datacollection1class.findByIdAndUpdate(req.params.id,
{
$set: {
varone: req.body.varone,
vartwo: req.body.vartwo,
varthree: req.body.varthree,
varfour: req.body.varfour
}
},
{
new:true
},
function(err, updatedDatacollection1classsingle) {
if(err){
res.send("Error updating Datacollection1class by id : "+err);
} else {
res.json(updatedDatacollection1classsingle);
}
});
});
// Delete a document
router.delete('/datacollection1class/:id', function(req, res) {
console.log('Deleting a datacollection1class');
Datacollection1class.findByIdAndRemove(req.params.id, function(err, deletedDatacollection1classsingle){
if (err) {
res.send("Error deleting Datacollection1class by id: "+err);
} else {
res.json(deletedDatacollection1classsingle);
}
});
});
Go to command prompt and using angular CLI create a class. Make sure Angular CLI is installed on your machine. Type in command prompt in your app folder
ng generate class datacollection1class
and hit enter. This will create a file named "datacollection1class.ts"
Inside datacollection1class.ts type the following code:
export class Datacollection1class {
_id: string;
varone: string;
vartwo: string;
varthree: string;
varfour: string;
}
You are all set. Now on your command prompt type:
ng build
Then on your command prompt type:
node server
Go to the browser and run "http://localhost:4200/api/datacollection1class" or if you have the id of the document, then "http://localhost:4200/api/datacollection1class/59305a02734d1d5068f2414e" or tey running it using postman
Feel free to ask questions. upvote if you liked the help.

Related

Strapi uploaded files are not displaying on website

I have many files which are stored in upload_file collection in mongodb and they have relations with related content types. However when I open Strapi CMS UI, I cannot see the file attached on its content type.
I am using Strapi v3.4.6 — Community Edition.
In the first picture is showing the my one of upload_file collection item. Its relation is shown in red circle.
In the second picture is showing the my main content type collection item. You see that its id and upload_file rel id is matching.
But in Strapi UI, this file is not linked to model. The file exists in file system of Strapi. However it is not visible
I can add this file manually, but is there any quick way to do this?
You need to migrate the database. We solved with a basic script.
Run http://localhost:3000/migrate
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
var dbName = "YOURDBNAME";
const express = require('express')
const app = express()
const port = 3000
var _db;
var _dbo;
var tables = {
"table1": "TabLE1",
"table2": "TABle2",
}
app.get('/migrate', (req, res) => {
res.send('Started!')
_dbo.collection("upload_file").find({}).toArray(function(err, result) {
if (err) throw err;
result.forEach(function (item) {
if (item.related.length > 0) {
var related = item.related[0];
var query = { '_id': related.ref };
var newvalues = { $set: {} };
newvalues.$set[related.field] = item._id;
var tableName = related.kind.toLowerCase();
_dbo.collection(tables[tableName]).updateOne(query, newvalues, function(err, res) {
if (err) throw err;
console.log(res != null ? res.ops : null);
});
}
})
// db.close();
});
})
MongoClient.connect(url, function(err, db) {
if (err) throw err;
_dbo = db.db(dbName);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Run http://localhost:3000/migrate
When uploading your image to strapi make sure your formData has these fields
const formData = new FormData();
formData.append('files', image);
formData.append('ref', 'contentTypeName');
formData.append('refId', dataItemId);
formData.append('field', 'image');

react add data from MongoDB to email

pretty new to react only been doing it for a couple of weeks and I'm working on a project for personal use to send an email to my email using nodemailer which I have managed to do. the next part I want to do is add data to the email that will come from my MongoDB database like the order number, customer name and status of the job I've searched high and low on youtube and google and not really finding anything on the issue
also, it only runs when I type node server.js and then it automatically sends the email which I don't want I want it to run when submit is clicked when a status is updated in the database.
Here is the code for what I have on server.js
require('dotenv').config();
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
let mailOptions = {
from: 'group2021#gmail.com',
to: 'edge#gmail.com',
subject: 'Project Update',
text: 'Hello {{name}} please find this email as an update to you project.'
};
transporter.sendMail(mailOptions, function(err, data) {
if(err) {
console.log('Error Occured!', err);
} else {
console.log('Email Sent!')
}
});
I'm not sure how your application looks like, I assume it's SPA react application.
I suggest you to create simple http server using Expressjs and creating endpoint which you will call from the client (react app) e.g. (the code is not tested is just an example)
const express = require('express');
const app = express();
const port = 3000;
const nodemailer = require('nodemailer');
app.get('/mail/:someID', async (req, res) => {
// someID is identifier to find data in db
// it will come from localhost:PORT/mail/>>someID<<
const { someID } = req.params;
let data;
try {
data = await mongoCol.FindOne({
/* query */
}); // reads data from mongo
} catch (err) {
return res.status(500).json(err);
}
// prepare content
var text =
'Hello {{name}} please find this email as an update to you project.\n' + data;
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
let mailOptions = {
from: 'group2021#gmail.com',
to: 'edge#gmail.com',
subject: 'Project Update',
text: text
};
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
console.log('Error Occured!', err);
return res.status(500).json(err);
} else {
console.log('Email Sent!');
return res.sendStatus(200);
}
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
You should add some kind of authorization to not allow other people to send email by your server.
also, it only runs when I type node server.js and then it automatically sends the email which I don't want
This happens because your code is not in function and any time you import or start file (module) it will execute.

ENOENT ERROR using fs.unlink in a Express.js Simple APP?

js.And i'm creating a simple blog in express.js.
I use Typicode/lowdb as database , to create/update/delete, posts based on the id on a data.json file.And use the slug data in the json array to create/update/delete markdown posts with the Node.js File System API.On the delete side of the markdown posts i get an error that i don't understand.
{ [Error: ENOENT, unlink 'C:\Users\path\to\publicfolder\undefined.md']
errno: -4058,
code: 'ENOENT',
path: 'C:\\Users\\path\\to\\publicfolder\\undefined.md' }
I'm using fs.unlink like this to remove markdown posts:
var oldSlug = "public/"+req.params.slug+".md";
fs.unlink(oldSlug, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file: " + oldSlug +"");
}
});
Here is some example of the code exposed by parts:
Example to create/update/delete Posts - Post.js
exports.index = function (req, res) {
res.render('post/index', { posts: db.list()});
};
exports.form = function (req, res) {
res.render('post/form');
};
exports.edit = function (req, res) {
var post = db.getById(req.params.id);
res.render('post/edit', {post: post})
}
exports.update = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.update({id: req.body.id, name: req.body.name, desc: req.body.desc,
slug: slugTitle});
//using this to rename and update markdown posts it work's
var oldPath = "public/"+req.body.slug+".md";
var newPath = "public/"+slugTitle+".md";
fs.unlink(oldPath, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file : oldPath ");
}
});
fs.writeFile(newPath, description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The post was updated as: newPath ");
}
});
res.redirect('/post');};
exports.remove = function (req, res) {
db.remove(req.params.id);
//using this to delete markdown posts i get the error
//changing req.params.slug to req.body.slug still gives the error
var oldSlug = "public/"+req.params.slug+".md";
fs.unlink(oldSlug, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the markdown file: " + oldSlug +"");
}
});
res.redirect('/post');};
Example on Server.js
app.get('/post', post.index);
app.get('/post/create', post.form);
app.post('/post/create', post.save);
app.get('/post/details/:id', post.details);
app.get('/post/edit/:id', post.edit);
app.post('/post/update', post.update);
app.get('/post/delete/:id', post.remove);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
Example of a index.jade
doctype
html
head
title
body
h1 Posts
ul
each item in posts
li Item #{item.name} - #{item.desc} - #{item.slug}
a(href='/post/details/#{item.id}') Details -
a(href='/post/edit/#{item.id}') Edit -
a(href='/post/delete/#{item.id}') Delete
div
p
a(href='post/create') Add new
The problem is on the exports.remove function in post.js file but why??I believe i'm identifying the markdown file to delete that corresponds to the Slug params from the document in the database or not? I Hope i'm making sense in the code.
The problem is that you are not passing the variable slug anywhere to your remove route. Since you are using GET it can't come from req.body, so you have to either pass it in the URL path or as query string.
Try changing these lines:
post.js
var oldSlug = "public/"+req.query.slug+".md";
index.jade
a(href='/post/delete/#{item.id}?slug=#{item.slug}') Delete

MEANJS mongoose model in request object

I've just started with meanjs. When I've taken a look at it server side module user profile controller, I find that mongoose model User is available in req object.
From where it has got added in req object?
Refer the code below, I wants to understand var user = req.user;, How user is added in req object?
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller.js'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Update user details
*/
exports.update = function(req, res) {
// Init Variables
var user = req.user;
var message = null;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
/**
* Send User
*/
exports.me = function(req, res) {
res.json(req.user || null);
};
In meanjs app.param([name], callback) is used, whenever a route with some id like articeId in parameter is accessed, app.param([name], callback) middleware is triggered. In meanjs it sets req.article like this.
app.param('articleId', articles.articleByID);
and in articleByID
exports.articleByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
if (err) return next(err);
if (!article) {
return res.status(404).send({
message: errorHandler.getErrorMessage(err)
});
}
req.article = article;
next();
});
};
more on app.param see http://expressjs.com/api.html#app.param
Passport’s authentication middleware sets req.user upon successful login.
See http://passportjs.org/guide/authenticate/.

node.js & express - global modules & best practices for application structure

I'm building a node.js app that is a REST api using express and mongoose for my mongodb. I've got the CRUD endpoints all setup now, but I was just wondering two things.
How do I expand on this way of routes, specifically, how do I share modules between routes. I want each of my routes to go in a new file, but obviously only one database connection as you can see i've included mongoose at the top of people.js.
Do I have to write out the schema of the model 3 times in my people.js? The first schema defines the model, then I list all the vars out in the createPerson and updatePerson functions. This feels like how I made php/mysql CRUD back in the day lol. For the update function, I've tried writing a loop to loop through "p" to auto detect what fields to update, but to no avail. Any tips or suggestions would be great.
Also, I'd love any opinions on the app as a whole, being new to node, it's hard to know that the way you are doing something is the most efficient or "best" practice. Thanks!
app.js
// Node Modules
var express = require('express');
app = express();
app.port = 3000;
// Routes
var people = require('./routes/people');
/*
var locations = require('./routes/locations');
var menus = require('./routes/menus');
var products = require('./routes/products');
*/
// Node Configure
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
});
// Start the server on port 3000
app.listen(app.port);
/*********
ENDPOINTS
*********/
// People
app.get('/people', people.allPeople); // Return all people
app.post('/people', people.createPerson); // Create A Person
app.get('/people/:id', people.personById); // Return person by id
app.put('/people/:id', people.updatePerson); // Update a person by id
app.delete('/people/:id', people.deletePerson); // Delete a person by id
console.log('Server started on port ' + app.port);
people.js
//Database
var mongoose = require("mongoose");
mongoose.connect('mongodb://Shans-MacBook-Pro.local/lantern/');
// Schema
var Schema = mongoose.Schema;
var Person = new Schema({
first_name: String,
last_name: String,
address: {
unit: Number,
address: String,
zipcode: String,
city: String,
region: String,
country: String
},
image: String,
job_title: String,
created_at: { type: Date, default: Date.now },
active_until: { type: Date, default: null },
hourly_wage: Number,
store_id: Number, // Inheirit store info
employee_number: Number
});
var PersonModel = mongoose.model('Person', Person);
// Return all people
exports.allPeople = function(req, res){
return PersonModel.find(function (err, person) {
if (!err) {
return res.send(person);
} else {
return res.send(err);
}
});
}
// Create A Person
exports.createPerson = function(req, res){
var person = new PersonModel({
first_name: req.body.first_name,
last_name: req.body.last_name,
address: {
unit: req.body.address.unit,
address: req.body.address.address,
zipcode: req.body.address.zipcode,
city: req.body.address.city,
region: req.body.address.region,
country: req.body.address.country
},
image: req.body.image,
job_title: req.body.job_title,
hourly_wage: req.body.hourly_wage,
store_id: req.body.location,
employee_number: req.body.employee_number
});
person.save(function (err) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "Person was not created." });
}
});
return res.send(person);
}
// Return person by id
exports.personById = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "That person doesn't exist." });
}
});
}
// Delete a person by id
exports.deletePerson = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
return person.remove(function (err) {
if (!err) {
return res.send(person.id + " deleted");
} else {
console.log(err);
return res.send(404, { error: "Person was not deleted." });
}
});
});
}
// Update a person by id
exports.updatePerson = function(req, res){
return PersonModel.findById(req.params.id, function(err, p){
if(!p){
return res.send(err)
} else {
p.first_name = req.body.first_name;
p.last_name = req.body.last_name;
p.address.unit = req.body.address.unit;
p.address.address = req.body.address.address;
p.address.zipcode = req.body.address.zipcode;
p.address.city = req.body.address.city;
p.address.region = req.body.address.region;
p.address.country = req.body.address.country;
p.image = req.body.image;
p.job_title = req.body.job_title;
p.hourly_wage = req.body.hourly_wage;
p.store_id = req.body.location;
p.employee_number = req.body.employee_number;
p.save(function(err){
if(!err){
return res.send(p);
} else {
console.log(err);
return res.send(404, { error: "Person was not updated." });
}
});
}
});
}
I have taken another approach here. Not saying it is the best, but let me explain.
Each schema (and model) is in its own file (module)
Each group of routes for a particular REST resource are in their own file (module)
Each route module just requires the Mongoose model it needs (only 1)
The main file (application entry point) just requires all route modules to register them.
The Mongo connection is in the root file and is passed as parameter to whatever needs it.
I have two subfolders under my app root - routes and schemas.
The benefits of this approach are:
You only write the schema once.
You do not pollute your main app file with route registrations for 4-5 routes per REST resource (CRUD)
You only define the DB connection once
Here is how a particular schema file looks:
File: /schemas/theaterSchema.js
module.exports = function(db) {
return db.model('Theater', TheaterSchema());
}
function TheaterSchema () {
var Schema = require('mongoose').Schema;
return new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
address: { type: String, required: true },
latitude: { type: Number, required: false },
longitude: { type: Number, required: false },
phone: { type: String, required: false }
});
}
Here is how a collection of routes for a particular resource looks:
File: /routes/theaters.js
module.exports = function (app, options) {
var mongoose = options.mongoose;
var Schema = options.mongoose.Schema;
var db = options.db;
var TheaterModel = require('../schemas/theaterSchema')(db);
app.get('/api/theaters', function (req, res) {
var qSkip = req.query.skip;
var qTake = req.query.take;
var qSort = req.query.sort;
var qFilter = req.query.filter;
return TheaterModel.find().sort(qSort).skip(qSkip).limit(qTake)
.exec(function (err, theaters) {
// more code
});
});
app.post('/api/theaters', function (req, res) {
var theater;
theater.save(function (err) {
// more code
});
return res.send(theater);
});
app.get('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.put('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.delete('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
return theater.remove(function (err) {
// more code
});
});
});
};
And here is the root application file, which initialized the connection and registers all routes:
File: app.js
var application_root = __dirname,
express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
http = require('http');
var app = express();
var dbProduction = mongoose.createConnection('mongodb://here_insert_the_mongo_connection_string');
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use('/images/tmb', express.static(path.join(application_root, "images/tmb")));
app.use('/images/plays', express.static(path.join(application_root, "images/plays")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.get('/api', function (req, res) {
res.send('API is running');
});
var theatersApi = require('./routes/theaters')(app, { 'mongoose': mongoose, 'db': dbProduction });
// more code
app.listen(4242);
Hope this was helpful.
I found this StackOverflow post very helpful:
File Structure of Mongoose & NodeJS Project
The trick is to put your schema into models directory. Then, in any route, you can require('../models').whatever.
Also, I generally start the mongoose db connection in app.js, and only start the Express server once the connection is up:
mongoose.connect('mongodb://localhost/whateverdb')
mongoose.connection.on('error', function(err) {
console.log("Error while connecting to MongoDB: " + err);
process.exit();
});
mongoose.connection.on('connected', function(err) {
console.log('mongoose is now connected');
// start app here
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
I'd take a look at this project https://github.com/madhums/node-express-mongoose-demo . It is a great example on how to build a nodejs application in a standard way.

Categories

Resources