Converting Url parameters to object id - express

How can Id gotten from request parameter in express be converted to object id for Mongoose
Let's say for instance
app("path/get_user_b
yid/:id6888",(req,
res)=>.{
//code to convert I'd
back to object...
}

you can call findById function to get a specific user as bellow
const mongoose = require('mongoose');
connst Schema = mongoose.Schema;
const User = new Schema({
name: String,
...
// other data
});
app.get('path/get_user_b yid/:id', (req, res) => {
cosnt id = req.params.id;
User.findById(id, function (err, user) {
if (err) {
return res.status(500);
}
return res.status(200).json(user);
});
});

Related

How to unselect a particular document in mongoose

I have access to userId and I want to get result without document of that particular user. How can I do this in mongoose?
async peopleyoumayknow(req, res) {
const {id} = req.params
const response = await userModel.find({}).sort({creation_date:-1}).limit(12)
return res.send(response)
}
Update your code to
async peopleyoumayknow(req, res){
const {id} = req.params
const response = await userModel.find({ _id: {"$ne": id}}).sort({creation_date:-1}).limit(12);
return res.send(response)
}

mongoose save by reference multiple document

I'd like to make new document by reference of two documents.
**app.post('/student_badge/register', async (req, res) => {
const name = req.body.name;
const category = req.body.category;
People.find({name: name}, '_id', function (err, doc) {
if (err) return handleError(err);
var obj = eval(doc);
id = obj[0]._id;
})
Badge.find({category: category}, 'points title', function (err, doc) {
if (err) return handleError(err);
var obj2 = eval(doc);
points = obj2[0].points;
title = obj2[0].title;
console.log(title + " " + points);
});
data = {
id: id,
title: title,
points: points
}
console.log("data: " + data);
const sbadge = new StudentBadge(data);
sbadge.
save()
.then(result => {
res.status(201).json({
message: 'Post created successfully!',
post: result
});
})
.catch(err => {
console.log(err);
});
});**
But I cannot call three variables like id, title, points to store them in 'data'.
How can I call variables?
Thanks
Your code does not work because the variables you are trying to access, i.e. id, title, points, are being set on a callback function that gets executed asynchronously.
I would suggest using async/await instead of callbacks so that you can thereafter use the data from the other documents you are querying in the same function. In addition, I suggest to use findOne() since you only access the first entry in db.
Something like the example below should work: (I have abstracted the middleware in a separate function for clarity to use with express)
const createStudentBadge = async (req, res, next) => {
const {name, category} = req.body;
let person, badge;
try {
person = await Person.findOne({name}); // shortcut for {name: name}
badge = await Badge.findOne({category});
} catch(err) {
// handle error
}
if (!person || !badge) {
// Handle case where no document has been found in db
// This case will not throw an error when calling find()
}
data = {
id: person._id,
title: badge.title,
points: badge.points
}
const studentBadge = new StudentBadge(data);
try {
await studentBadge.save();
} catch(err) {
// handle error
}
res.status(201).json({
message: 'Post created successfully!',
post: studentBadge
});
}
app.post('/student_badge/register', createStudentBadge);
If you wanted to perform the querying in parallel, you could make use of Promise.all() and run both queries at the same time. More info can be found at MDN documentation

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.

hash the password in the routes file and update

This is PUT method I want to hash my password(using passport) & and update it.
router.put('/reset/:token', function(req, res) {
console.log('listening');
User.findOneAndUpdate({resetPasswordToken:req.params.token},{
password: req.body.password,
resetPasswordToken: undefined,
resetPasswordExpires: undefined
},function(err,user) {
if(err) {
console.log(err + 'is here');
} else {
res.json(user);
}
});
});
I want to hast the variable only password.How can I hash within this method & then update it.
I'm assuming you are using Mongoose. First, create a pre method inside your Schema.
UserSchema
const mongoose = require('mongoose')
, bcrypt = require('bcrypt-nodejs')
, SALT_WORK_FACTOR = 10;
const UserSchema = new mongoose.Schema({
... // schema here
});
/**
* Hash password with blowfish algorithm (bcrypt) before saving it in to the database
*/
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password'))
return next();
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(SALT_WORK_FACTOR), null);
next();
});
mongoose.model('User', UserSchema);
And then in your route:
router.put('/reset/:token', function(req, res, next) {
User.findOne({resetPasswordToken: new RegExp('^' + req.params.token + '$', "i")}, function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(422).json({errors: [{msg: 'invalid reset token'}]});
user.resetPasswordToken = '';
user.resetPasswordExpires = '';
user.password = req.body.password;
user.save().then(function (user) {
return res.status(200).json(user);
});
});
});

Mongoose Schema Array/Object .post

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