Solved. See below for the answer.
I'm trying to get only a limited amount of results.
While the second one works, the first one doesn't. What's missing here?
First query
app.get('/ind', function (req, res) {
youtube.where('status', 0).fetch(function (qb) {
qb.limit(10);
}).then(function (data) {
data = data.toJSON();
});
});
Second query
app.get('/photos', function (req, res) {
user.where('id', 1).fetch({
withRelated: [{
'photos': function (qb) {
qb.limit(2);
}
}]
}).then(function (data) {
data = data.toJSON();
res.send(data);
});
});
Solved.
All you need is to add a query() before fetchAll() and define your limit inside this query().
app.get('/ind', function (req, res) {
youtube.where('status', 0).query(function (qb) {
qb.limit(10);
}).fetchAll().then(function (data) {
data = data.toJSON();
res.render('youtube', {
mi: data
});
});
});
Related
These are my codes. I am wondering why is my first GET request only working but the 2nd one is not?
I am trying to pull data from 2 table but want to render them to the same page for 2 different fields.
// GET ALL CATEGORIES
app.get("/company", function (req, res) {
db.Category.findAll({
attributes: ["categoryName"],
raw: true
}).then(function (data) {
// res.json(dbCategory);
var dbCategory = {
dbCategory: data
};
console.log(dbCategory);
res.render("companyPage", dbCategory);
});
});
// GET ALL MANUFACTURER
app.get("/company", function (req, res) {
db.Manufacturer.findAll({
attributes: ["manufacturerName"],
raw: true
}).then(function (data) {
var dbManufacturer = {
dbManufacturer: data
};
console.log(dbManufacturer);
res.render("companyPage", dbManufacturer);
});
});
The GET endpoint is not working because you have defined same route.
this problem can be solved using
1.use different route as explain in above answer
2.if you want both operation should be perform on /company then combine two operation under single GET endpoint
check sample code for more reference:
// GET ALL CATEGORIES
app.get("/company", function (req, res) {
db.Category.findAll({
attributes: ["categoryName"],
raw: true
}).then(function (dbCategory) {
// GET ALL MANUFACTURER
db.Manufacturer.findAll({
attributes: ["manufacturerName"],
raw: true
}).then(function (dbManufacturer) {
var dbStuff = {
dbCategory,
dbManufacturer,
msg: "Christmas Toy Store"
};
console.log(dbStuff);
res.render("companyPage", dbStuff);
});
});
});
Because you're defining same route, you can change the second route and update it accordingly with fields.
// GET ALL CATEGORIES
app.get("/company", function (req, res) {
db.Category.findAll({
attributes: ["categoryName"],
raw: true
}).then(function (data) {
// res.json(dbCategory);
var dbCategory = {
dbCategory: data
};
console.log(dbCategory);
res.render("companyPage", dbCategory);
});
});
// GET ALL MANUFACTURER
app.get("/company/manufacturer", function (req, res) {
db.Manufacturer.findAll({
attributes: ["manufacturerName"],
raw: true
}).then(function (data) {
var dbManufacturer = {
dbManufacturer: data
};
console.log(dbManufacturer);
res.render("companyPage", dbManufacturer);
});
});
Because you get the first path '/compagny'.
If you want the two datas with the same path, you should write all in the same get function.
Try this :
app.get("/company", async function (req, res) {
const dataCategory = db.Category.findAll({
attributes: ["categoryName"],
raw: true
});
const dataManufacturer = db.Manufacturer.findAll({
attributes: ["manufacturerName"],
raw: true
});
const [dbCategory, dbManufacturer] = await Promise.all([dataCategory,dataManufacturer]);
res.render("companyPage",{
dbCategory,
dbManufacturer
});
});
How can I put res in a normal function i.e not an exported one which is not part of routes?
function createNewStudent(v,callBackOne){
if (callBackOne) {
studentInfo.callBackOneStudent = callBackOne;
}
// common filter json
var filterjson = common.defaultFilterJson();
filterjson['active'] = true;
filterjson['email'] = v.email;
// student initialization
var student = new Student(v);
async.waterfall([
function (done) {
student.save(function (err) {
if (!err) {
studentInfo.callBackOneStudent();
Employee.update({_id: student.created_by},{"$push": { "students": student._id } }).exec(function (err, employee) { });
done();
}
});
}
}
});
},
function (done) {
var url = config.mailer.studentActivateUrl + student._id;
---error is here-----
res.render('modules/users/server/templates/student-confirmation-email', {
name: student.first_name + ' ' + student.last_name,
appName: 'GAIPP',
url: url
}, function (err, emailHTML) {
done(err, emailHTML, student);
});
}
});
My error is 'res' is not defined. Can anyone please help me to solve this error?
The only way that you can put res in a function is if you somehow supply it to that function at runtime. Remember that res is meaningful only in request handling. Outside of the request handler your function couldn't even know which request to respond to because there might be several requests served at the same time.
If you want to have a function that has access to res then you have those options:
Use a nested function in your request handler, e.g.
app.get('/foo', function (req, res) {
function x() {
// you can use res here
}
x();
});
Add res as an argument:
function x(res) {
// you can use res here
}
app.get('/foo', function (req, res) {
x(res);
});
Another option would be to add a callback to your function that would be passed by the handler:
function x(args, cb) {
// you cannot use res here
// but you can call the callback:
cb(null, 'something');
}
app.get('/foo', function (req, res) {
x(function (err, data) {
if (err) {
// handle error
}
// use res here with data supplied by x()
res(data);
});
});
Instead of using callback your x() function could also return a promise.
I have a problem with accessing multiple controller at the same time,
example I'm accessing the method "access" while "access" is active, I can't use/access the method "other" or other controllers in the client side,
but when the looping in "access" is done, I can use other methods or controllers, is SailsJs controller Single Threading?
access: function (req, res) {
// Assume that I'll generate 1k data and I dont have problem about that
// my problem is while generating 1k data i cant access my other Controller/Method
// any solution about my problem thanks :)
// NOTE** this is just a example of the flow of my program
// In creating data Im using Async
while(x <= 1000) {
Model.create(etc, function (err, ok) {
if(err) console.log(err)
});
x++;
}
res.view('view/sampleview');
},
other: function (req, res) {
res.view('view/view');
},
All controllers and actions are avaible in sails.contollers variavel Mike sails.controllers.mycontroller.access (req, res);
run in parallel, all at same time:
access: function (req, res) {
var createFunctions = [];
while(x <= 1000) {
createFunctions.push(function(done) {
Model.create(etc).exec(function (err, ok) {
if(err) return done(err); // err
done(); //success
});
})
x++;
}
async.parallel( createFunctions, function afterAll(err) {
sails.controllers.mycontroller.other (req, res);
//res.view('view/sampleview');
});
},
other: function (req, res) {
res.view('view/view');
},
run in series, one by one:
access: function (req, res) {
var createFunctions = [];
while(x <= 1000) {
createFunctions.push(function(done) {
Model.create(etc).exec(function (err, ok) {
if(err) return done(err); // err
done(); //success
});
})
x++;
}
// run in series, one by one
async.series( createFunctions, function afterAll(err) {
sails.controllers.mycontroller.other (req, res);
//res.view('view/sampleview');
});
},
other: function (req, res) {
res.view('view/view');
},
users = [];
.on('result', function(user) {
async.waterfall([
function(cb) {
get_comm(user.post_id, function(comms) {
user.comm = comms;
users.push(user);
cb(users);
})
},
], function(users, cb) {
console.log(users); // it prints out
});
})
.on('end', function() {
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
users: users // empty []; !!
});
}
});
So I want after finishing on result loop to print out all data but array is full in result loop and empty out of it.
I'm assuming the on method is from an instance of a EventEmitter. If so the callbacks passed to on aren't async capable.
You're code is doing async within them.
I am working on a NodeJs project for the first time. And now i am stuck with the function returning values through JS and getting values to use in express.
var dbitems = "before fn";
function refreshData(callback) {
db.open(function (err, db) {
if (!err) {
db.collection('emp').find().toArray(function (err, items) {
dbitems = items;
callback(JSON.stringify(items));
});
}
else {
console.log("Could not be connnected" + err);
dbitems = {"value":"not found"};
}
});
}
}
refreshData(function (id) { console.log(id); });
This function retrieves values perfectly from refreshData and writes into console. But what I need is to use the retrieved value to send into express html file from this function by "returnedData"
exports.index = function (req, res) {
var valrs = refreshData(function (id) {
console.log(JSON.parse(id)); ---this again writes data perfectly in the console
});
console.log(valrs); -------------------but again resulting in undefined
res.render('index', { title: 'Express test', returnedData: valrs });
};
Any help would be appreciated.
Thanks & Regards,
Luckyy.
You need to render this after the database request finishes.. so it needs to be called from within the callback.
exports.index = function (req, res) {
refreshData(function (id) {
res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
});
};
it's asynchronous so you can't just put values in order, needs to go through the callbacks.