Mongoose Schema Array/Object .post - express

I have this codes:
// Morosos.js
var mongoose = require('mongoose');
const MorososSchema = new mongoose.Schema({
idlor: String,
comunidad: String,
vivienda: String,
demandado: String,
importe: String,
datos: [{ fecha: String, dato: String }],
date: { type: Date, default: Date.now },
});
mongoose.model('Morosos', MorososSchema);
module.exports = mongoose.model('Morosos');
&&
// MorososController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var Morosos = require('./Morosos');
router.post('/', function (req, res) {
console.log(req.body.datos.fecha + " " + req.body.comunidad);
Morosos.create({
idlor : req.body.idlor,
comunidad : req.body.comunidad,
vivienda : req.body.vivienda,
demandado: req.body.demandado,
importe: req.body.importe,
datos: [{fecha: req.body.datos.fecha, dato: req.body.datos.dato}] ,
date: Date.now()
},
function (err, user) {
if (err) return res.status(500).send("There was a problem adding the information to the database. Error: "+err);
res.status(200).send(user);
});
});
// RETURNS ALL THE USERS IN THE DATABASE
router.get('/', function (req, res) {
Morosos.find({}, function (err, users) {
if (err) return res.status(500).send("There was a problem finding the users. Error: ");
res.status(200).send(users);
});
});
module.exports = router;
When I use "POST" on "Postman" with x-www-form-urlencoded with this info:
idlor:LOR02/16
comunidad:XXXXX
vivienda:XXXXX
demandado:YYYYY
importe:XXXXX€
datos:{[fecha:28/09/2016,dato:Cristina]}
After trying lot of different ways I can't save the "array" datos or show the "array" datos on the server.
I put a code console.log(req.body.datos.fecha + " " + req.body.comunidad); but it throw me undefined at req.body.datos.fecha.
I'm blocked and I don't know how to solve this. Thanks!

Try sending:
idlor:LOR02/16
comunidad:XXXXX
vivienda:XXXXX
demandado:YYYYY
importe:XXXXX€
datos[fecha]:28/09/2016
datos[dato]:Cristina

Related

Azure functions: Exception: TypeError: connection.query is not a function

I have a simple Azure function trying to get all data from a SQL table. The connection is successful and I can connect to the database, but whenever I run the get request, I end up with an error
Exception: TypeError: connection.query is not a function
Stack: TypeError: connection.query is not a function
This is the line throwing the error
connection.query(query, (err, results, fields) => {
this is my index.js azure get function
const express = require('express')
const bodyParser = require('body-parser')
let connection = require('../configs/dbConfig')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
module.exports = async function (context, req, res) {
const query = 'SELECT * FROM entrys'
connection.query(query, (err, results, fields) => {
if (err) {
const response = { data: null, message: err.message, }
res.send(response)
}
const pokemons = [...results]
const response = {
data: pokemons,
message: 'All entrys successfully retrieved.',
}
res.send(response)
})
}
Am using tedious as the connection driver. my dbconfig
let Connection = require('tedious').Connection;
let pool = {
server: "localhost", // or "localhost"
authentication: {
type: "default",
options: {
userName: "sa",
password: "root",
}
},
options: {
database: "testing",
encrypt: false
}
};
var connection = new Connection(pool);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection
what am I doing wrong, thank you in advance
You should use Request to query.
In the official documentation, I did not see the usage of connection.query. It is not recommended that you use tedious when you are not very familiar with it. I have a sample code here, I hope it helps you.
You can download my Sample Code which use mssql package.
var express = require('express');
var router = express.Router();
let connection = require('../configs/dbConfig')
var Request = require('tedious').Request;
/* GET users listing. */
router.get('/', function(req, res, next) {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
res.send('respond with a resource');
});
module.exports = router;
Test Result:

How to change password using passport-local.Strategy and crypto in expressjs?

Below is the code I am trying: index.jsand its not working while changing the password in terms of salt and hash.(saving them in database) I am keep getting the error as setPassword is not defined. Also I think I am committing code errors as well. I want the exact route code for change password using 'passport-local' Strategy.
P.S. I am able to successfully register the user and login as well. I just want to give him the option to change the password.
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
User.findOne({id: req.user.id}, function (err, data) {
console.log("came inside api changePassword else condition inside User.findOne");
if (err) {
console.log(err);
}
else {
data.setPassword(req.body.newPass, function(err,datas){
if(datas) {
data.save(function (err,datass) {
if (err) {
res.render('settingsClient', {errorMessages: err});
} else {
console.log("Hash and Salt saved");
}
});
}
else {
console.log("setPassword error"+ err);
}
});
}
})
This is
Models (user.js) with which I am saving the password at the start of registration of user as hash and salt.
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};
userSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return this.hash === hash;
};
module.exports = mongoose.model('User', userSchema);

How to use async and await with Express and MongoDB

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongodb = require('mongodb');
const app = express();
app.use(cors())
app.use(bodyParser.json());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
app.post("/register" , (req, res) => {
const { displayName, email, password } = req.body;
if (!email || !displayName || !password) {
return {code: 400, msg: "incorrect form submission"}
}
let insertedid = null
MongoClient.connect(url, (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var myobj = { displayName: displayName, email: email, password: password };
dbo.collection("customers").insertOne(myobj)
.then(res => {
insertedid = res.insertedId
})
});
res.json({id: insertedid})
})
app.listen(process.env.PORT || 3000, ()=> {
console.log(`App is running on port 3000`);
})
Here, I am storing data inside db and sending the last inserted id
to the frontend.
However, id is returning null.
How can I use async and await to solve this issue?
You can modify your post function using async await like this:
app.post("/register", async (req, res) => {
const { displayName, email, password } = req.body;
if (!email || !displayName || !password) {
return {code: 400, msg: "incorrect form submission"}
}
let insertedid = null ;
MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var myobj = { displayName: displayName, email: email, password: password };
var result = await dbo.collection("customers").insertOne(myobj);
insertedid = result.insertedId;
res.json({ id: insertedid})
});
})

How to get two tables data in Node.js with object inside other object

I have two tables and I need data in this format. How is this Possible?
My Tables
Required Output
{
"id":"1",
"name":"akhil",
"pics": [
{
"pic1": "123.jpg",
"pic2": "123.jpg"
}
]
}
Generally I use this for getting data from single table
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('./config');
var VerifyToken = require('./VerifyToken');
const mysql = require('mysql');
app.use(express.json());
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'sample'
});
app.get('/usersdata', VerifyToken, (req, res) => {
let id = req.userId;
console.log(req.userId);
connection.query("select * from users", function (error, results, fields) {
if (error) throw error;
else {
res.send({"result": results});
}
});
})
My Solution:
app.get('/usersdata', (req, res) => {
connection.query("select u.id, u.name, p.pic1, p.pic2 from users u, pics p where u.usersid=p.id", function (error, results, fields) {
if (error) throw error;
else {
let data = results;
let newResult = {};
results.map(row => {
if(newResult[row.id]) {
newResult[row.id].pics.push(row.pic1, row.pic2)
} else {
newResult[row.id] = { id: row.id, name: row.name, pics: [row.pic1, row.pic2] };
}
})
res.send({ "result": Object.values(newResult) });
}
});
})
I would use an ORM instead of writing query myself. Check this link used for a project saved lot of time and code was cleaner.

Constructing document yields semi-empty result

After executing Customer.create({customerName: 'John'}), the following document is created without error and without the 'customerName' node.
Can anyone tell me why this seemingly simple document creation call yields a semi-blank document? The document in the response from Mongoose is the same as it is in the database itself.
I can't tell if I'm using Mongoose incorrectly or Express incorrectly. Thanks in advance for your help.
{ __v: 0, _id: 5452dc48d687bad849d70816 }
routes/customer.js
var mongoose = require( 'mongoose' );
var Customer = mongoose.model( 'Customer');
exports.create = function(req, res) {
Customer.create({
customerName: 'John'
}, function(err, customer) {
if (err) return err;
console.log('Customer created', customer);
res.send(customer);
});
}
schema/customer.js
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
db.js
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/CustomerDatabase';
mongoose.connect(dbURI);
var customerSchema = require( '../schema/customer.js' );
var Customer = mongoose.model( 'Customer', customerSchema);
routes.js
function SetupRoutes(app, PATH) {
var db = require('../model/db.js')
var customer = require( '../routes/customer.js' );
app.post('/Customer', customer.create);
}
module.exports.SetupRoutes = SetupRoutes;
You need to export customerSchema from customer.js so that when db.js requires that file, its value is the exported schema:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = customerSchema;
However, the more typical pattern is to create the model in customer.js and then export that:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = mongoose.model('Customer', customerSchema);