How to construct mongoose Find from url query string? - express

I have an object schema as
var book = new Schema ({
name: {type: String},
code: {type: String}
});
Sample content is
{
name: "Jungle Book",
code: "Jungle"
}
{
name: "Java Book",
code: "Java"
}
I have a http GET request to my Express server as
http://localhost:port/api/book?name=Jung
This API invocation is expected to return all books that have the name starting with "Jung"
In my experess implementation, I have
exports.getBooks = function(req, res, next) {
var query = require('url').parse(req.url, true).query;
Book.find({"name": /^query.name/}).exec(function(err, books){
if(err){ res.status(400).json(
{ success: false,
message: 'Error processing request '+ err
});
}
res.status(201).send(books);
});
};
I receive an empty array, the search is not successful. However when I do an exact match like below its successful.
Book.find({"name": query.name})....
Pleases suggest how to perform a 'find' with 'starts with' operation from a query parameter.

Mongoose supports regexp, so an other option is:
let regexp = new RegExp("^" + query.name);
Book.find({ name: regexp });
Or try:
let data = {"name": /^query.name/};
Book.find(data, function(err, books) {
if(err) {
res.status(400).json({
success: false,
message: 'Error processing request ' + err
});
};
res.status(201).send(books);
});

Related

Can't find mongoose validation error within express error object

I'm using mongoose js and trying to insert a new document into a mongodb. I'm passing the data object to express using Axios. When I get a validation error, the express server identifies the problem very easily. It returns an error productCode: ValidatorError: Path 'productCode' is required.
The error that is returned to express is a huge object and I can't find the validation error in it. Can someone tell me what I'm missing in my catch error?
UPDATED
Path: Express axios Post catch error
const product = {
productCode: '1a',
productName: 'product x'
};
async function createProduct(product) {
axios
.post(
`http://localhost:3000/myroute`,
product
)
.then((res) => {
console.log('res', res.data.productCode);
return res.data.productCode;
})
.catch((error) => {
// console.log('err', err.response);
if (error.response) {
/*
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
// console.log(error);
});
}
UPDATE
Path: Server
const product = new Product(req.body);
product
.save()
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
console.log('err', err);
res.status(500).json({ error: err.reason });
});
Path: Model
var productSchema = new Schema(
{
productCode: {
type: String,
required: true
},
productName: { type: String, default: '' }
},
{ collection: 'products', timestamps: true, versionKey: false }
);

Can't Post data from postman to database with express

I am unable to Post data from postman to mysql database
I'm using express
I have tried using Body and Raw x-wwww-form-urlencoded
Here is my code (Yes everything is in the same file I know it's not a good thing I'm sorry)
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// connection configurations
var dbConn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testexpress'
});
// connect to database
dbConn.connect();
// Add a new user
app.post('/user', function (req, res) {
let user = req.body.user;
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", { user: user }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
// set port
app.listen(3000, function () {
console.log('Node app is running on port 3000');
});
module.exports = app;
here is my screenshot error from Postman and my database
Modify your code like this. It should work
// Add a new user
app.post('/user', function (req, res) {
let user = [req.body]
console.log(user);
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", user, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
Your code is showing this error message error:true, message: 'Please provide user because everytime in your code the condition if (!user) is executed, because let user = req.body.user is going to give undefined value so you are going to get that error and the rest of the code will never execute then
.

Difference between POST and GET (hapijs)

I'm new to the hapijs. Can someone tell me what's the difference between POST and GET in hapijs? For some reason my POST method doesn't work at all so I do is INSERT via GET function.
GET:
server.route({
method: 'GET',
path: '/index/{orderId}',
config: {
handler: test,
validate: {
params: {
orderId: Joi.string()
.required()
.description('Order indentifier')
}
}
}
});
And test function:
function test (request, reply) {
console.log(request.params.orderId);
var params = {orderId: request.params.orderId}
connection.query('INSERT QUERY HERE', function (err, res, fields) {
if (err) throw error;
console.log(res);
reply(res);
});
}

How can I override builtin login method in Loopback?

I've created a new User model, based on builtin one. I'm trying this:
module.exports = function(TiUser) {
TiUser.on('dataSourceAttached', function(obj) {
var login = TiUser.login;
TiUser.login = function(credentials, include, cb) {
var result = login.apply(this, credentials);
// Do my stuff
cb(null, my_data);
};
});
};
But I can't get it working... What is wrong? or how could this be done right?
Thanks
You may want to consider adding an afterRemote() hook to login(). Now you can achieve to add role( using Role model ) to user. For example:
TiUser.afterRemote('login', function(ctx, next) {
//add role to the user.
next();
});
At the end I've created a new method instead of overriding a current one:
module.exports = function(TiUser) {
TiUser.auth = function(credentials, include, fn) {
var self = this;
self.login(credentials, include, function(err, token) {
authInfo = {
token: token
};
fn(err, authInfo);
});
};
TiUser.remoteMethod(
'auth',
{
description: 'Login method with Role data information embedded in return',
accepts: [
{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'include', type: ['string'], http: {source: 'query' },
description: 'Related objects to include in the response. ' +
'See the description of return value for more details.'}
],
returns: {
arg: 'accessToken', type: 'object', root: true,
description: 'User Model'
},
http: {verb: 'post'}
}
);
};

how to resolve error in sub documents mongoose/express

I am developing a web application based on the Mean Stack, but I have a care with Add and Edit operations, particularly with sub documents of the Field "order", the console tells me that "reference" is undefined on the line "order.reference" : req.body.order.reference,
, I don't know how to for sub documents. When I add or modify any of "order" fields I got an error, but when I add all the Fields without exception it works. here is my mongoose diagram:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var ContactSchema = new Schema({
name: {type: String},
order: {
reference : {type : String},
adresse : {type : String} ,
product : {type : String}
}
});
var ContactModel = mongoose.model('Contact', ContactSchema);
mongoose.connect('mongodb://localhost/contact');
exports.add = function(req, res) {
var contact = req.body;
contact = new ContactModel({
name: req.body.name,
"order.reference" : req.body.order.reference,
"order.adresse" : req.body.order.adresse,
"order.product" : req.body.order.product
});
contact.save(function (err) {
if (!err) {
res.json(true);
} else {
console.log(err);
res.json(false);
}
});
return res.jsonp(req.body);
};
exports.edit = function (req, res) {
var id = req.params.id;
if (id) {
ContactModel.findById(id, { upsert: true }, function (err, contact) {
contact.name = req.body.name,
contact.order.reference = req.body.order.reference,
contact.order.adresse = req.body.order.adresse ,
contact.order.product = req.body.order.product
contact.save(function (err) {
if (!err) {
res.json(true);
} else {
res.json(false);
console.log(err);
}
});
});
}
};
Thank you for your time, I can provide angular code and html
You'll probably want to use Express and the body parser:
How do you extract POST data in Node.js?
Note: I believe this was written for Express 3 and the syntax is a little different for Express 4