sequelize includes not returning data - node.js

I am trying to get data mapped with empid from 2 tables viz-skillsrepo and certifications and render it to frontend,I am getting all data from certifications table,but i need data only of the empid which i send in request
tried using includes method
app.get('/updateprofile/:id', function (req, res) {
db.skillsrepo.find({
where: { employeeId: req.params.id },
include: [
{
model: db.certifications
},
{
model: db.attachments
},
{
model: db.project
}
]
}).then(result => {
if (result != null) {
res.render('updateprofile', {
user: result,
eid: req.params.id,
});
console.log("**********", result)
}
})
});
This is the Schema:
var skillsrepo = exports.skillsrepo = connection.define('skillsrepo', {
firstname: {
type: Sequelize.STRING(23)
},
lastname: {
type: Sequelize.STRING(23)
},
highQual: {
type: Sequelize.STRING(23)
},
fivekeystrenghts: {
type: Sequelize.TEXT
},
domain: {
type: Sequelize.STRING(23)
},
technicalskills: {
type: Sequelize.STRING(23)
},
typesoftesting: {
type: Sequelize.STRING(23)
},
employeeId: {
type: Sequelize.INTEGER(11),
references: {
model: 'employeemastertablee',
key: 'id'
}
}
});
skillsrepo.hasMany(certifications, {
foreignKey: "employeeId"
});
certifications.belongsTo(skillsrepo, {
foreignKey: "employeeId"
});

Related

Why does the child's resolve function not contain the result of the parent's resolve function?

I've tried to isolate this example and I hope it's ok. I know, this isn't great code, but I hope you get the drift.
For the time being the resolvers return a static result object.
Here's my problem:
The result of the company resolve function should be passed on the user's resolve function. But that ain't happenin' and I wonder what I am missing.
const GraphQL = require('graphql');
const UserType = new GraphQL.GraphQLObjectType({
name: 'User',
fields: {
givenName: { type: GraphQL.GraphQLString },
familyName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
},
});
const CompanyType = new GraphQL.GraphQLObjectType({
name: 'Company',
fields: {
legalName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
employees: { type: new GraphQL.GraphQLList(UserType) },
},
});
const queryDef = new GraphQL.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: UserType,
args: {
id: { type: GraphQL.GraphQLID },
givenName: { type: GraphQL.GraphQLString },
familyName: { type: GraphQL.GraphQLString },
city: { type: GraphQL.GraphQLString },
},
resolve: (parent, args, context, info) => {
console.log('parent should provide company object', parent);
// currentyl parent is undefined
return {
id: 10,
givenName: 'test',
};
},
},
company: {
type: CompanyType,
args: {
id: { type: GraphQL.GraphQLID },
},
resolve: (parent, args, context, info) => {
return {
id: 3,
legalName: 'legal test name',
city: 'company location',
};
},
},
},
});
const schema = new GraphQL.GraphQLSchema({ query: queryDef });
const companyQuery = `
{
company(id: 1) {
city
employees {
familyName
}
}
}`;
GraphQL.graphql(schema, companyQuery).then( (companyResult) => {
console.log(companyResult);
} ).catch( (err) => {
console.error(err);
});

Update name in nested object array

I'm new to MongoDB using angular as frontend. I'm trying to update a name in nested object array.
My Schema is as follows:
const mongoose = require("mongoose");
const projectDragDropSchema = mongoose.Schema({
_idProject: mongoose.Schema.Types.ObjectId,
projectTitle: { type: String, required: true },
boards: [
{
_idBoard: mongoose.Schema.Types.ObjectId,
boardTitle: { type: String, required: false },
cards: [
{
type: new mongoose.Schema(
{
cardId: { type: mongoose.Schema.Types.ObjectId, required: true },
cardTitle: { type: String, required: false },
}
// { minimize: false }
),
required: false,
},
],
required: false,
},
],
});
module.exports = mongoose.model("ProjectDragDrop", projectDragDropSchema);
I'm trying to update the cardTitle.
I have written the multiple updates to it, but unable to find the correct one.
The Router:
router.patch(
"/updateProjectBoardCardName/:_idProject/:_id",
projectBoardsCards.updateCardName
);
The code:
exports.updateCardName = (req, res) => {
const idProject = req.params._idProject;
const boardID = req.params._id;
projectDragDropSchema
.update(
{ _idProject: idProject, "boards._id": boardID },
{ cards: { $elemMatch: { _id: req.body.params } } },
{ $set: { "cards.$.cardTitle": req.body.params } }
)
.exec()
.then((result) => {
console.log(result);
res.status(200).json(result);
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
};
Thanks in advance.

Cast to ObjectId failed for value at path for model error

This is my Profile Schema:
const mongoose = require('mongoose');
const ProfileSchema = new mongoose.Schema({
user: {
// Special field type because
// it will be associated to different user
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
This is my view api. It doesn't work. it only return Cast to ObjectId failed for value { 'experience._id': '5edcb6933c0bb75b3c90a263' } at path _id for model profile
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findById({
'experience._id': req.params.viewexp_id,
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
How can I fix this? I tried looking at the stackoverflow of the same errors. still it doesn't seem to work.
and this is what I am trying to hit
The problem is that you have to convert your string _id to mongoose object id using this function mongoose.Types.ObjectId and my suggestion is to use findOne function instead of findById,
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
let id = mongoose.Types.ObjectId(req.params.viewexp_id);
const exp = await Profile.findOne(
{ "experience._id": req.params.viewexp_id },
// This will show your sub record only and exclude parent _id
{ "experience.$": 1, "_id": 0 }
);
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findOne({
'experience._id': mongoose.Types.ObjectId(req.params.viewexp_id),
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
You are saving object id . but your param id is string. convert it in ObjectId. Please check my solution.
router.post(
"/",
[
auth,
[
check("status", "status is required").not().isEmpty(),
check("skills", "skills is required").not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubuername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin,
} = req.body;
const profileFileds = {};
profileFileds.user = req.user.id;
if (company) profileFileds.company = company;
if (website) profileFileds.website = website;
if (location) profileFileds.location = location;
if (bio) profileFileds.bio = bio;
if (status) profileFileds.status = status;
if (githubuername) profileFileds.githubuername = githubuername;
if (skills) {
profileFileds.skills = skills.split(",").map((skill) => skill.trim());
}
//Build profile object
profileFileds.social = {};
if (youtube) profileFileds.social.youtube = youtube;
if (twitter) profileFileds.social.twitter = twitter;
if (facebook) profileFileds.social.facebook = facebook;
if (linkedin) profileFileds.social.linkedin = linkedin;
if (instagram) profileFileds.social.instagram = instagram;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFileds },
{ new: true }
);
return res.json(profile);
}
//Create profile
profile = new Profile(profileFileds);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send("server Error");
}
}
);

add to collection in sails

Maybe my question is very simple and superficial
But please, guide me
my Place Model is:
module.exports = {
attributes: {
title: {
type: 'string',
},
body: {
type: 'string',
columnType: 'text',
},
address: {
type: 'string',
columnType: 'text',
},
x_map: {
type: 'number',
columnType: 'float'
},
y_map: {
type: 'number',
columnType: 'float'
},
like: {
type: 'number',
columnType: 'integer'
},
dis_like: {
type: 'number',
columnType: 'integer'
},
visited: {
type: 'number',
columnType: 'integer'
},
emtiaz: {
type: 'number',
columnType: 'integer'
},
tags: {
type: 'string',
},
city:{
collection: 'city',
via: 'place_owner'
},
},
};
And my City Model is:
module.exports = {
attributes: {
title: {
type: 'string',
},
ostan_owner :{
model: 'ostan'
},
place_owner: {
model: 'place'
}
},
};
And my place controller is:
create: function (req, res, next) {
Place.create(req.params.all, function place_created(err,new_place){
if(err && err.invalidAttributes) {
err = validator(Place, err);
return res.json({'status':false, 'errors':err.Errors});
}
else{
new_place.add('city',req.param('city'));
new_place.save(function (err) {
if(err){
return res.json({'status':false,'errors':err});
}
else {
res.json({'status':true,'result':new_place});
}
});
}
});
},
now whene i try to create new place and add new city to collection it give me Error:
TypeError: Cannot read property 'add' of undefined
at place_created (C:\Programing_workspace\gardeshgar_sailsV1\gardeshgar\api\controllers\PlaceController.js:28:19)
whene i use model_X.addToCollection i recive same error
i use sails v 1.0 and i am new in sails.js
please Help me
Sails.js 1.0 does not support .add() and .save() anymore.
Please use .addToCollection() instead.
await Place.addToCollection(new_place.id, 'city').members(req.param('city'));
The other problem is that sails.js 1.0 does not automatically fetch the created/updated Object (new_place in your case).
You need to add { fetch: true } in order the get the created object.
For example:
User.create({...}, function(err, createdUser) {
//...
}, { fetch: true });
Or using await:
var createdUser = await User.create({...}).fetch();
I think, in your case, the solution should be:
create: function (req, res, next) {
Place.create(req.params.all, function place_created(err,new_place){
if(err && err.invalidAttributes) {
err = validator(Place, err);
return res.json({'status':false, 'errors':err.Errors});
}
else{
await Place.addToCollection(new_place.id, 'city').members(req.param('city')).exec(function (err) {
if(err){
return res.json({'status':false,'errors':err});
}
else {
res.json({'status':true,'result':new_place});
}
});
}
}, { fetch: true });
},

Sequelize: OR between parent where clause and child where clause

I have 2 models:
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.STRING,
},
});
User.associate = (models) => {
User.hasOne(models.Profile, {
foreignKey: {
name: 'user_id',
},
});
};
const Profile = sequelize.define('Profile', {
name: {
type: DataTypes.STRING,
},
avatar: {
type: DataTypes.STRING,
},
}, {
tableName: 'profiles',
freezeTableName: true,
timestamps: false,
});
Profile.associate = (models) => {
Profile.belongsTo(models.User, {
foreignKey: {
name: 'user_id',
},
});
};
I would like to get all users where the email address OR the name matches a certain condition. Something like:
User
.all({
where: {
email: {
$like: filter
},
},
include: [{
model: Profile,
where: {
name: {
$like: filter
},
},
}],
})
.then(users => res.status(200).send(users))
.catch(error => {
return res.sendStatus(500);
});
but it returns all users where user.email AND profile.name matches the condition. I would like to have OR between the 2 where clause.
Is it possible?
Note:
I'm using Sequelize 4.0.0.
Update:
In case of anybody else struggles with this, the solution is:
User
.all({
where: {
$or: {
email: {
$like: filter
},
'$Profile.name$': {
$like: filter
}
}
},
include: [{
model: Profile,
}],
})
.then(users => res.status(200).send(users))
.catch(error => {
return res.sendStatus(500);
});
In case if anyone else is looking for this, here is how I managed to solve it:
User
.all({
where: {
$or: {
email: {
$like: filter
},
'$Profile.name$': {
$like: filter
}
}
},
include: [{
model: Profile,
}],
})
.then(users => res.status(200).send(users))
.catch(error => {
return res.sendStatus(500);
});
Thanks #Ninja Coding for confirming the solution.

Resources