Converting Array to bulk Create in nodejs with Sequelize - mysql

This is my req.body json data from angularjs controller:
{
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
}
i want to get gsm values from req.body
I want to make the above structure into this type:
[{phoneno:123457801;sender:'ifelse';message:'Hello Test'},{phoneno:123450987;sender:ifelse;message:'Hello Test'}]
then only i am able to insert in mysql.

I think it will helpful to you!...
var body={
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
};
var new_req_body=[];
for(var i=0;i<body.phoneno.length;i++){
var new_arr={
sender:body.sender,
message:body.message,
phoneno:body.phoneno[i].gsm
};
new_req_body.push(new_arr);
}
console.log(new_req_body);

Related

Append data to an object upon Sequelize Model Fetch

I have a service function to get users from my MySQL database using Sequelize ORM and i would to like to append fullName to the Users.
const filterUsers = async ([...users]:IUsers[]) => {
let searchAttributes = {};
if (users) { searchAttributes = { [Op.or]: users }; }
const filteredUsers = await User.findAll({
raw: true,
nest: true,
where: { ...searchAttributes },
include: [{
model: Club,
as: 'homeClub',
}, {
model: Club,
as: 'awayClub',
}] });
return filteredUsers as unknown as IUsersWithTeams[];
};
FilteredUsers response:
filteredUsers =
[
{
id: 1
name: 'John',
LastName: 'Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
What i would like to receive:
const expectedUserResponse = [
{
id: 1
name: 'John',
LastName: 'Mayer',
FullName: 'John Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
FullName: 'Adam Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
How can i do that ? Thank you very much if you can help me ;)
You need to use a virtual field, see documentation and my other answer to the similar question. It seems the official documentation has the example that perfectly fits your request:
const { DataTypes } = require('#sequelize/core');
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});

How to map an object from JSON file to another object?

Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.

NodeJS- ExpressJS mongoose API POST Request with foreign key

I'm trying to create an REST API in JSON. I have 2 models, an business and an address. An Address is part of a business
When I try to create a POST request with the following JSON
{
"name" :"GRIT",
"adress":
{
"street" : "test",
"number": "5",
"city":"leuven",
"postalcode":"2900",
"country":"BEL"
}
}
I get the following error
{
"error": {
"errors": {
"adress": {
"message": "Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectID",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress",
"reason": {
"message": "Cast to ObjectId failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectId",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress"
}
}
},
"_message": "Business validation failed",
"message": "Business validation failed: adress: Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "ValidationError"
}
}
These are my mongoose models
const mongoose = require('mongoose');
const businessSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name:{
type: String,
required: true,
},
adress:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Adress',
required:true
}
});
module.exports = mongoose.model('Business', businessSchema);
const mongoose = require('mongoose');
const adressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
street:{
type: String,
required: true
},
number:{
type: int,
required: true
},
city:{
type: String,
required: true
},
postalCode:{
type: String,
required: true
},
country:{
type: String,
required: true
}
});
module.exports = mongoose.model('Adress', adressSchema);
The following is my Post request
//POST -> Register a business
router.post('/',function(req,res){
const business = new Business({
id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress:{
id:new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country:req.body.adress.country
}
});
business
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Business created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
What did I do wrong? Does the adress doesn't save or do I link the two models wrong with eachother
I am using MongoDB as a Datbase
Take a look at the mongoose docs.
You are trying to set a ObjectId property with an Adress object. What you have to do is first save your adress object, and then reference it inside your business object.
PS: You should name your ids as _id since thats the convention used in MongoDB.
It would look something like this:
let adress = new Adress({
_id: new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country: req.body.adress.country
});
adress
.save()
.then(() => {
let business = new Business({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress: adress._id
});
business
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: "Business created"
});
});
});

Implementing Promises using Bluebird

I have a function which needs to be implemented with Bluebird Promises but unable to work it out. Here is a pseudo code
exports.addEmployees=function (req,res){
var data = [
{
firstName: 'XXXXX',
lastName: 'V',
phone: '9999999999',
dateOfBirth: '2010-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
{
firstName: 'YYYYY',
lastName: 'K',
phone: '8888888888',
dateOfBirth: '2011-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
];
async.each(data, function(item,callback){
req.db.Employee.create(item, callback);
},function(err){
if(err){
res.send("Error!");
}
res.send("Success!");
}
);
}
Thanks
Something like
var Promise = require("bluebird")
var data = [
{
firstName: 'XXXXX',
lastName: 'V',
phone: '9999999999',
dateOfBirth: '2010-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
{
firstName: 'YYYYY',
lastName: 'K',
phone: '8888888888',
dateOfBirth: '2011-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
];
Promise.map(data, function(item) {
return req.db.Employee.create(item)
.then(function(id){ return id })
.catch(MyError, function(e) {
e.item = item;
throw e;
})
}).then(function(idList) {
res.send("Success!");
}).catch(MyError, function(e) {
console.log("Operation failed on " + e.item + ": " + e.message);
res.send("Error!");
});
You need to define myError to make this work (https://github.com/petkaantonov/bluebird/blob/master/API.md#catchfunction-errorclassfunction-predicate-function-handler---promise)
P.S. Sure, req.db.Employee.create(item) should support promises, so probably you will need to promisify it: https://github.com/petkaantonov/bluebird/blob/master/API.md#promisepromisifyallobject-target--object-options---object

C# to JSON serialization using JSON.Net

I have a C# List which looks like this:
var reqUsers = from user in users
select new
{
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
email = user.email
};
I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):
var json = JsonConvert.SerializeObject(reqUsers);
With the above code I get a json string like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
however here is what I need to get : since I am using handlebars templating -
var testdata = {
users: [
{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
How can use the Serializer to name the JSON array as above ?
Use:
var json = JsonConvert.SerializeObject(new { users = reqUsers });
use:
var json= new JavaScriptSerializer().Serialize(reqUsers);