how get dependent dropdown data in node with postgres - node.js

I have done following thing, using nodejs exoress with postgresql. For this api my input will be country id, modelname of country & for left join another model name im
{
"id": 1,
"module": "state_master",
"leftJoinmodule": "country_master"
}
exports.getStateDataByCountryId = async (req, res) => {
if (!req.body.module) {
return response.fail(res, "Model Name is Required", "");
}
const id = req.body.id;
var module = req.body.module;
var leftJoinmodule = req.body.leftJoinmodule;
console.log(leftJoinmodule)
if (Model[module]) {
Model[module]
.findAll({
raw: true,
where: {
country_id: id,
active: 1,
},
include: [{
model: Model.leftJoinmodule,
as: 'country'
},]
// include: [{
// model: Model.leftJoinmodule,
// as: 'country',
// where: {
// id: id
// }
// }]
})
.then((allStateMasterData) => {
return response.success(res, "All State Data", allStateMasterData);
})
.catch((err) => {
return response.catchError(res, err.message, "", module);
});
} else {
return response.fail(res, "Invalide Model Name", "");
}
};
getting below error
{
"status": 500,
"code": 0,
"message": "Include unexpected. Element has to be either a Model, an Association or an object.",
"data": ""
}
anyone plz help on this issue

Related

Node.js - How to get associated model data using graphql?

In Node.js app, I am using graphql to get the list of data. I have created two models called School and Grade. Association for these models like School has many Grades and Grade belongs to School.
While querying I am getting null value for associated model.
In model school.js,
module.exports = (sequelize, Sequelize) => {
const School = sequelize.define("school", {
name: {
type: Sequelize.STRING,
},
email: {
type: Sequelize.STRING,
},
});
School.associate = function (models) {
School.hasMany(models.Grade, { foreignKey: "school_id" });
};
return School;
};
In typeDefs.graphql,
type Query {
getSchoolDetails: [School]
getSchoolDetail(id: ID!): School
getGradeDetails: [Grade]
}
type School {
id: ID!
name: String
email: String
grades: [Grade]
}
type Grade {
id: ID!
school_id: ID!
name: String
school: School
}
In resolvers.js,
const Query = {
getSchoolDetails: async () => {
try {
const schools = await school.findAll();
return schools;
} catch (err) {
console.log(err);
}
},
getSchoolDetail: async (root, { id }) => {
try {
const scl = await school.findByPk(id);
return scl;
} catch (err) {
console.log(err);
}
},
getGradeDetails: async () => {
try {
const grades = await grade.findAll({});
return grades;
} catch (err) {
console.log(err);
}
},
}
In playground when I query like,
query {
getSchoolDetails{
id
name
email
grades{
name
}
}
}
Output for this is,
{
"data": {
"getSchoolDetails": [
{
"id": "1",
"name": "Rotary West School",
"email": "rotary#gmail.com",
"grades": null
},
{
"id": "2",
"name": "Excel Public School",
"email": "excel#gmail.com",
"grades": null
},
]
}
Same way when I query to get Grades will get school as null. I am learning nodejs relations with graphql, please help me to solve this.
You have to use include with your queries in resolvers.js file like below
getSchoolDetails: async () => {
try {
const schools = await school.findAll({
include: [{ model: Grade }],
});
return schools;
} catch (err) {
console.log(err);
}
},
This Will get all the grades associated with schools
And if you want to include school with grade you have to associate grade with school using Grades belongsTo school

How to get validation erros from multi models in sequelize + node.js

I'm trying to create models with including related models. Then validation is failed i get only 1 error instead of all fails of validation.
at example is
[
{
"loads": {
"name": "Name is required"
}
}
]
How can i get all validation fails with all related models? Like
[
{
"model1": {
"name": "Name is required"
}
},
{
"model2": {
"name": "Name is required"
}
},
{
"model3": {
"name": "Name is required"
}
},
{
"etc": {
"name": "Name is required"
}
}
]
Here is my router function:
router.post('/', [checkAuth], async (req, res) => {
let {
name="",
weight="",
volume="",
packing_type="",
price_request="",
note="",
visible="",
Origin={city_id: '', date_from: ''}, // Origin object
Destination={city_id: ''}, // Destination object
} = req.body;
result = await db.transaction((t) => {
return LoadModel.create({
user_id: user_id,
name: name,
weight: weight,
volume: volume,
packing_type: packing_type,
price_request: price_request,
note: note,
visible: visible,
origin: Origin,
destination: Destination,
},{ include: [
OriginModel, DestinationModel
], transaction: t})
}).then(result => {
res.status(201).json(result);
}).catch(Sequelize.ValidationError, (err) => {
res.status(400).json(err.errors.map(item => {
return {
[item.instance._modelOptions.tableName]: {[item.path]: item.message}
};
})); // How can i get all validation errors for returning it?
}).catch(badError => {
res.status(500).json(badError);
})
validateErrors.catch(err => {
console.log(err);
})
});
Maybe there is a way to return validation errors from promise to global object? Or something else...

Is there any way to rename the path while we select the complex object from mongodb using mongoose in nodejs?

I want to rename the path of the fields which are coming from the response.
My Query:
const allLeads = await Lead.find().select({
"basic.mobileNumber": 1
});
res.send({ allLeads });
Response I'm Getting
{
"allLeads": [
{
"_id": "5d9f0e2118d1a445bae077aa",
"basic": {
"mobileNumber": "1223654789"
}
},
{
"_id": "5d9f16a8cba7744902acb422",
"basic": {
"mobileNumber": "1123654789"
}
}
]
}
how I want the response
{
_id: 5d9f0e2118d1a445bae077aa,
mobileNumber: "1223654789"
},
{
_id: 5d9f16a8cba7744902acb422,
mobileNumber: "1123654789"
}
So is there any way yo archive this using mongoose?
I did it like this. Is there any other and better way to do this?
let simpleLeadInfo = [];
await SwatiLead.find()
.select({
_id: 1,
"basic.mobileNumber": 1,
})
.exec((err, data) => {
if (!err) {
for (lead in data) {
const obj = {
id: data[lead]._id,
mobileNumber: data[lead].basic.mobileNumber,
};
simpleLeadInfo = [...simpleLeadInfo, obj];
}
return res.send({ error: false, status: "OK", simpleLeadInfo });
}
});

Problem with ottoman not resolving the references

I have two models in my ottoman 1.0.5 setup. One holds contact info which includes an emails array of docs and then the email doc. I can insert new contacts fine as well as emails in docs and the corresponding link in the contact doc for the new email.
Here is my model
const ottoman = require("ottoman")
ottoman.bucket = require("../app").bucket
var ContactModel = ottoman.model("Contact",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
first_name : "string",
last_name : "string",
emails: [
{
ref:"Email"
}
]} )
var EmailModel = ottoman.model("Email",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
type : "string",
address : "string",
name: "string"
} )
module.exports = {
ContactModel : ContactModel,
EmailModel : EmailModel
}
Now to get an contact and all its emails i use this function
app.get("/contacts/:id", function(req, res){
model.ContactModel.getById(req.params.id,{load: ["emails"]}, function(error, contact){
if(error) {
res.status(400).json({ Success: false , Error: error, Message: ""})
}
res.status(200).json({ Success: true , Error: "", Message: "", Data : contact})
})
})
Which returns me this
{
"Success": true,
"Error": "",
"Message": "",
"Data": {
"timestamp": "2019-01-30T23:59:59.188Z",
"emails": [
{
"$ref": "Email",
"$id": "3ec07ba0-aaec-4fd4-a207-c4272cef8d66"
}
],
"_id": "0112f774-4b5d-4b73-b784-60fa9fa2f9ff",
"first_name": "Test",
"last_name": "User"
}
}
if i go and log the contact to my console i get this
OttomanModel(`Contact`, loaded, key:Contact|0112f774-4b5d-4b73-b784-60fa9fa2f9ff, {
timestamp: 2019-01-30T23:59:59.188Z,
emails: [ OttomanModel(`Email`, loaded, key:Email|3ec07ba0-aaec-4fd4-a207-c4272cef8d66, {
timestamp: 2019-01-31T00:36:01.264Z,
_id: '3ec07ba0-aaec-4fd4-a207-c4272cef8d66',
type: 'work',
address: 'test#outlook.com',
name: 'Test Outlook',
}),
OttomanModel(`Email`, loaded, key:Email|93848b71-7696-4ef5-979d-05c19be9d593, {
timestamp: 2019-01-31T04:12:40.603Z,
_id: '93848b71-7696-4ef5-979d-05c19be9d593',
type: 'work',
address: 'newTest#outlook.com',
name: 'Test2 Outlook',
}) ],
_id: '0112f774-4b5d-4b73-b784-60fa9fa2f9ff',
first_name: 'Test',
last_name: 'User',
})
This shows that emails was resolved but why does it not show up in the returned json. On the other hand if i return contact.emails i get the resolved emails just fine. So i hope someone can shed some light on what i am missing here
I asked a similar question on the couchbase forum, and I also found out the solution:
(a slight difference that the result of my search is an array not an object like in your case)
forum.couchbase.com
app.get("/assets", (req, res) => {
AssetModel.find({}, { load: ["assetModelId", "assetGroupId", "assetTypeId"] }, (err, results) => {
if (err) return res.status(400).send("no asset found");
const assets = [];
results.map(asset => {
assets.push({...asset});
});
res.status(200).send(assets)
});
});

How to perform update in mongoose

I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks
My mongoose code,
exports.updatestudent = function (req, res) {
var student = new Student(req.body);
var data = {};
var id = req.params;
var params = req.body;
var item = {
'name': params.name,
'rollnumber': params.rollnumber,
'class': params.class,
'city': params.city
};
Student.update({ _id: id },{ $set: item }, function (err, result) {
if (err) {
console.log('err');
}
if (result) {
data = { status: 'success', error_code: 0, result: result, message: 'Article updated successfully' };
res.json(data);
}
});
};
my schema,
var StudentSchema = new Schema({
name: {
type: String
},
rollnumber: {
type: String
},
class: {
type: String
},
city: {
type: String
},
status: {
type: String
},
_id: {
type: Schema.ObjectId
}
});
/**
* Hook a pre validate method to test the local password
*/
mongoose.model('student', StudentSchema, 'student');
my result in postman,
{
"status": "success",
"error_code": 0,
"result": {
"ok": 0,
"n": 0,
"nModified": 0
},
"message": "Article updated successfully"
}
I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks
It seems you forgot to specify the key.
Replace
var id = req.params;
By
var id = req.params.id;
Make sure that you are getting your id in var id = req.params;
And I am sure you will not get your id like this
check your req.params; values and give your correct id in the query
Update
var item = {};
if (params.name) {
item.name = params.name;
}
if (params.rollnumber) {
item.rollnumber = params.rollnumber
}
Student.update({
_id: id
}, {
$set: item
}, function(err, result) {
if (err) {
console.log('err');
}
if (result) {
data = {
status: 'success',
error_code: 0,
result: result,
message: 'Article updated successfully'
};
res.json(data);
}
});

Resources