sequelize express table association/relation belongsTo - database

I have two tables, called employs and employ_detail.
I want to use relation for these two tables. I want to connect it using belongsTo. I've followed some tutorial but I am unable to do it.
Anybody help me.
exports.getEmployee = function(req, res) {
db.employs.findAll({
include: [
{
models: db.employ_detail
}
]
})}
.then(function(employs){
const resObj = employs.map(function(employs) {
//tidy up the employs data
return Object.assign(
{},
{
id: employs.id,
name: employs.name,
department: employs.department,
salary: employs.salary.map(function(employ_detail) {
//tidy up the post data
return Object.assign(
{},
{
id: employ_detail.id,
emp_id: employ_detail.emp_id,
name: employ_detail.name,
phone: employ_detail.phone
}
)
})
});
});
res.json(resObj)
});
and this is my db.js file..
'use strict';
var Sequelize=require('sequelize');
var path=require('path');
var sequelize =new Sequelize('company', 'root', 'welcome123$', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.employs = require(path.resolve('./models/employee'))(sequelize, Sequelize);
db.employ_detail = require(path.resolve('./models/employ_detail.js'))(sequelize, Sequelize);
//Relations
db.employ_detail.belongsTo(db.employs);
//db.employs.hasMany(db.staffs);
module.exports = db;

Need use options.
Example:
model.belongsTo(DIR.OrganizationModel, {
foreignKey: 'organization_id',
targetKey: 'organization_id',
constraints: false,
});
http://docs.sequelizejs.com/class/lib/associations/belongs-to.js~BelongsTo.html

Related

Typeorm synchronize throws QueryFailedError: Could not drop constraint. See previous errors

I'm trying to connect to a Microsoft SQL DB having synchronize: true option within TypeORM but it seems it doesn't work for some reason and I can't figure out why.
main.module.ts
providers: [
{
provide: "OMS_DB",
useFactory: async () => {
const connection = new DatabaseConnection(
new DatabaseConfiguration("OMS_DATABASE"),
[OMSOrderDto, OMSOrderLinesDto],
false
);
if (await connection.connect()) {
return connection;
}
return null;
},
},
]
database.connection.ts
constructor(
private configuration: DatabaseConfiguration,
private entities?: any,
private synchronize = false
) {}
/**
* Creates the actual connection
*/
async connect(): Promise<boolean> {
const config: DataSourceOptions = {
name: this.configuration.name,
type: "mssql",
host: this.configuration.hostname || "localhost",
port: this.configuration.port || 1433,
username: this.configuration.username,
password: this.configuration.password,
database: this.configuration.database,
entities: this.entities,
synchronize: false,
//logging: "all",
extra: {
trustServerCertificate: true,
},
};
this.logger.debug(
`Connecting to MSSQL Database ${this.configuration.hostname} / ${this.configuration.database}`
);
try {
this.connection = new DataSource(config);
await this.connection.initialize();
this.logger.log(`Conected to DB: ${this.configuration.hostname} / ${this.configuration.database}!`);
return true;
} catch (ex) {
this.logger.error(`Failed to connect to the database: ${this.configuration.name}`);
this.logger.error(ex);
}
return false;
}
Throwing Error:
Could not drop constraint. See previous errors.
I don't see any other errors.

mongodb sending userid's in an array as a query and return the json object of the users present in collection

I have a collection of online users here goes its model
var SessionDetailSchema = mongoose.Schema({
providerID: {
type: String
},
firstName: {
type: String
},
email: {
type: String
},
status: {
type: String
}
},{ timestamps: true });
var sessionDetail = module.exports = mongoose.model('OnlineUser', SessionDetailSchema);
I am trying to send an array of providerID's so that I wanted to check the collection which all providerId's are present and return me those providerID details.
and this is what I tried
router.post('/sessiondetails:find', function (req, res, next) {
console.log(req.body.providerID)
sessionDetail.find({ "providerID": { $in: req.body.providerID} }, function (err, users) {
if (users) {
console.log(users)
} else {
console.log("not there")
}
})
})
unfortunately, I am getting the only first providerid response for multiple times.
i am sending the array from the postman it looks like this
{
"providerID":["1090867867720278", "104761648907225164100", "114316680403119099502", "103668441331122956874"]
}
can some help me? thanks in advance.

azure mobile services calling sql server stored procedure and get a requestTimeout 15000ms error

I keep getting this error:
{"name":"RequestError","message":"Timeout: Request failed to complete in 15000ms","code":"ETIMEOUT","number":"ETIMEOUT","precedingErrors":[]}
How do I increase the timeout for my request?
I am not sure if this is coming from the sql server database or from the node.js service?
How do I see what is happening with sql server from azure?
I have sql server management studio and visual studio so i can login to my database, but don't see how to increase timeout etc.
Are there any parameters I set in node.js to increase timeout?
I found this:
http://azure.github.io/azure-mobile-apps-node/global.html#dataConfiguration
and presume I have to set something in my query object?
My node.js API that I call, searchService.js
var HttpStatus = require('http-status-codes');
module.exports = {
"post": function (req, res, next) {
var resultSet = {
TotalRecords: 0,
Results: null
};
var parameters = [
{ name: 'forumId', value: req.body.forumId },
{ name: 'registrantId', value: req.body.registrantId },
{ name: 'userId', value: req.azureMobile.user.id },
{ name: 'exclusive', value: req.body.exclusive },
{ name: 'type', value: req.body.type },
{ name: 'categoryIds', value: req.body.categoryIds.join(",") },
{ name: 'locationIds', value: req.body.locationIds.join(",") },
{ name: 'unitIds', value: req.body.unitIds.join(",") },
{ name: 'priceIds', value: req.body.priceIds.join(",") },
{ name: 'delimiter', value: "," }
];
console.log("parameters = " + JSON.stringify(parameters));
var query = {
sql: "exec SearchServicesStrictTotal #forumId, #registrantId, #userId, #exclusive, #type, #categoryIds, #locationIds, #unitIds, #priceIds, #delimiter",
parameters: parameters
};
req.azureMobile.data.execute(query)
.then(function(result) {
console.log("got result " + JSON.stringify(result));
resultSet.TotalRecords = result[0].Total;
res.status(HttpStatus.OK).send(resultSet);
}).catch(function(error){
console.log("error one " + JSON.stringify(error));
res.status(HttpStatus.BAD_REQUEST).send(error);
});
}
};
The default for request timeout is 15000 ms. To increase the timeout for the request you could try to put this to your app.js file.
var mobileApp = azureMobileApps({
homePage: true,
data: {
requestTimeout: 60000
}
});
The app.js file will look like this.
var express = require('express'),
azureMobileApps = require('azure-mobile-apps');
var app = express();
var mobileApp = azureMobileApps({
homePage: true,
data: {
requestTimeout: 60000
}
});
mobileApp.tables.import('./tables');
mobileApp.api.import('./api');
mobileApp.tables.initialize()
.then(function () {
app.use(mobileApp); // Register the Azure Mobile Apps middleware
app.listen(process.env.PORT || 3000); // Listen for requests
});
Hope it helps.

"User is not authorized" on meanjs

I would like to ask if there is anyone getting the same response on JSON format:
Objectdata: "User is not authorized"headers: (name) {status: 403statusText: "Forbidden"
Scenario:
User A post a product and add comment on the product.
Result: Successful.
User B comment on the same product:
Result: User is not authorized.
The code I'm using to update the product comment is here:
applicationname/`
// Add comment to Product
$scope.comment = function(){
// console.log("name: ",$scope.user);
// console.log("textarea: ",this.commentarea);
var comment = {
name: $scope.product.user.displayName,
text: this.commentarea
};
$scope.product.comments.push(comment);
$scope.product.$update(function() {
console.log('success update');
}, function(errorResponse) {
console.log('success error', errorResponse);
});
};
This is the server side.
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
If your Products schema looks like this:
var ProductSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
comments: [{
type: String,
default: '',
trim: true
}]
});
And you have restricted your products route in your app/routes/products.server.routes.js file like so:
app.route('/products/:productId')
.get(products.read)
.put(users.requiresLogin, products.hasAuthorization, products.update)
.delete(users.requiresLogin, products.hasAuthorization, products.delete);
Then a non-authorized user cannot add a comment because they can't update the Product record.
You probably want to create a separate CommentsSchema and use the Mongoose ObjectId type to create a one-to-many relationship with the product:
var CommentSchema = new Schema({
product: ObjectId,
content: {
type: String,
default: '',
trim: true,
required: 'Content cannot be blank'
},
})
That will preserve the security of your product and allow non-authorized users to comment, but would require you to do slightly more complex queries to get your comments in your product view.

Populate method in mongoose virtual: nothing is being returned. [duplicate]

I have two mongoose schemas as follow:
var playerSchema = new mongoose.Schema({
name: String,
team_id: mongoose.Schema.Types.ObjectId
});
Players = mongoose.model('Players', playerSchema);
var teamSchema = new mongoose.Schema({
name: String
});
Teams = mongoose.model('Teams', teamSchema);
When I query Teams I would to get also the virtual generated squad:
Teams.find({}, function(err, teams) {
JSON.stringify(teams); /* => [{
name: 'team-1',
squad: [{ name: 'player-1' } , ...]
}, ...] */
});
but I can't get this using virtuals, because I need an async call:
teamSchema.virtual('squad').get(function() {
Players.find({ team_id: this._id }, function(err, players) {
return players;
});
}); // => undefined
What is the best way to achieve this result?
Thanks!
This is probably best handled as an instance method you add to teamSchema so that the caller can provide a callback to receive the async result:
teamSchema.methods.getSquad = function(callback) {
Players.find({ team_id: this._id }, callback);
});

Resources