i have a model that uploads a file with some data in the field. All i want to do is to upload the file and take the file path as string and make a create query to another model and send back the response with the data sent as response in create query. Here is my code. It is not modifying.
var loopback = require('loopback');
var app = module.exports = loopback();
module.exports = function(Container) {
Container.beforeRemote('upload', function(context, user, next) {
next();
});
Container.afterRemote('upload', function(context, affectedInstance, next) {
var container = affectedInstance.result.files.file[0].container;
var val;
if(container=='profilepic')
{
var fileName = affectedInstance.result.files.file[0].name;
var FirstName= affectedInstance.result.fields.FirstName[0];
var LastName = affectedInstance.result.fields.LastName[0];
var Email = affectedInstance.result.fields.Email[0];
var Password = affectedInstance.result.fields.Password[0];
var account = Container.app.models.Account;
account.create({
FirstName:FirstName,
LastName:LastName,
Email:Email,
Password:Password,
UserPicture:'/server/storage/'+container+'/'+fileName,
},function(err,ant){
if(err)
console.log(err);
// Modifies the context
var res= JSON.parse(JSON.stringify(ant));
context.result={
data:res
}
console.log(context.result); // result shows the desired value
});
}
next();
});
};
Finally i have got the desired response. The problem was that the call back next() is executed before the modify operation. so i moved the next to the end of the create query.
var loopback = require('loopback');
var app = module.exports = loopback();
module.exports = function(Container) {
Container.beforeRemote('upload', function(context, user, next) {
next();
});
Container.afterRemote('upload', function(context, affectedInstance, next) {
var container = affectedInstance.result.files.file[0].container;
var val;
if(container=='profilepic')
{
var fileName = affectedInstance.result.files.file[0].name;
var FirstName= affectedInstance.result.fields.FirstName[0];
var LastName = affectedInstance.result.fields.LastName[0];
var Email = affectedInstance.result.fields.Email[0];
var Password = affectedInstance.result.fields.Password[0];
var account = Container.app.models.Account;
account.create({
FirstName:FirstName,
LastName:LastName,
Email:Email,
Password:Password,
UserPicture:'/server/storage/'+container+'/'+fileName,
},function(err,ant){
if(err)
console.log(err);
// Modifies the context
var res= JSON.parse(JSON.stringify(ant));
context.result={
data:res
}
console.log(context.result); // result shows the desired value
next(); // Call back;
});
}
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.