How to pass variables in node js? - node.js

Here I'm passing id which stored in m, please help me how to pass id. and call that page using that id. I'm using the embedded JavaScript template as a view engine please help.
$.each(products, function(index, product ) {
var m= product['_id'];
//document.write(alert(m));
string += '<tr><td>'+(index+1)+'</td><td>'+product['_id']+'</td><td>'+product['name']+'</td><td>'+product['category']+'</td><td>'+product['price']+'</td><td>'+product['manufacturer']+'</td><td>Update </td></tr>';
});
route code
app.get('/profile/dashboard/update/:m',function (req,res,next) {
console.log("hi"+req.params.m);
});

string += '<tr><td>'+(index+1)+'</td><td>'+product['_id']+'</td><td>'+product['name']+'</td><td>'+product['category']+'</td><td>'+product['price']+'</td><td>'+product['manufacturer']+'</td><td>Update </td></tr>';
It will work

You need to use this quotes `` for template string;
as example:
var m = 1;
var string = `id: ${m}`

`... <a href=/profile/dashboard/update/${product['id']}>Update</a> </td></tr>`
You need to wrap your whole string in backticks and pass the variables as written above ( ${var_name} ). See this answer for more info. This isn't a NodeJS question, more of a Javascript question itself.

Related

How to get the id from the given lines of code?

{
acknowledged: true,
insertedId: new ObjectId("612d9d08db9c20f031033478")
}
This was the JSON format I got while I added a file and some other things to MongoDB and I want to get this id separately to save the file to another folder.
Can anyone please explain this?
I believe this question was answered by Vikas in this thread How to get value from specific key in NodeJS JSON [duplicate]
Edited The Answer. Now Its working for above object in question
You can use following function to access the keys of JSON. I have
returned 'mm' key specifically.
function jsonParser(stringValue) {
var string = JSON.stringify(stringValue);
var objectValue = JSON.parse(string);
return objectValue['mm'];
}
if this is a JSON String, at first of all you have to parse it to object liertal, then you can access the specified property you mentioned, so you can do like the following:
function parseJsonString(jsonString) {
// first parse it to object
var obj = JSON.parse(jsonString);
// now access your object property/key
var id = obj.insertedId;
}
If your doing it on mongodb shell or Robo3T then, the line of code would be:
db.collection_name.find({},{insertedId:1})
This is related to projection. 1 represents you want to display it as your output.
In your case as you want only the value of your object id to get displayed, you have to use .valueOf() ; that is ObjectId().valueOf().
-> insertedId: new ObjectId("612d9d08db9c20f031033478")
-> ObjectId("612d9d08db9c20f031033478").valueOf()
->
-> 612d9d08db9c20f031033478
Your can refer this : https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/ site for your reference.
So you can use this .valueOf() in your code and get the id saved in the document

Sailsjs: dynamic tableName in model

I am building my first sailsjs and nodejs application, and it great :)
My situation, I have about 100 tables with the same stucture, I would like to decide "on the fly" which table to load.
my first thought was use somehow a dynamic class names. But I dont know how to do this with nodejs, maybe some one have an idea.
So I would create 100 "modelName".js files in my models folder.
I can use this in browser
window["fileName"].find()....
But I don't have any window object in nodejs
Second idea was to pass the tableName to the model, the problem is, I have to reinit the model, don't know how.
Any solutions?
Found a solution
var modelName = req.param('p');
this[modelName].find()...
Own answer by author is correct, but I will add something just for people who will use it in the future - you can get modelName from req.options.model when you are using Blueprints.
Unfortunately you can't use this[modelName] as option is giving you model name starting with small letter, so first you have to upper case first letter with e.g. var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1);
and then you are free to use this[modelName].whateverYouNeed
I used it for generic policy to let user editing only his own group elements.
var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1)
var elementID = null
if (req.params.id) { // To handle DELETE, PUT
elementID = req.params.id
}
if (req.body.id) { // To handle POST
elementID = req.body.id
}
this[modelName].findOne({
id: elementID
}).exec(function(err, contextElement) {
if(err) {
return res.serverError(err)
}
if(contextElement.group=== req.user.group.id) {
sails.log('accessing own: ' + modelName)
return next()
}
else {
return res.forbidden('Tried to access not owned object')
}
})
An alternative:
sails.models[Model].findOne({...})
Make sure to have your "Model" name as string in lowercase. It works like accessing a property inside an object
Another option that worked for me:
var modelName = "User";
global[modelName].find()....

How to convert the html object to string type?

I use jQuery method to get some type of html object:
var content = $('#cke_ckeditor iframe').contents().find('.cke_show_borders').clone();
Then I want to convert it to string type:
console.log(content[0].toString());
but the result is:
[object HTMLBodyElement]
How can I turn it into real string?
By the way, can I turn the converted html string to the html object?
I believe you want to use Element.outerHTML:
console.log(content.outerHTML)
I had the same problem.
var docString = "<html>"+content.documentElement.innerHTML+"</html>"
You can use this content[0].prop('outerHTML')
It worked for me
Reference : How do you convert a jQuery object into a string?
You can try the following:
content.text();
The correct way to Convert a jQuery object into a string:
var content = $('#cke_ckeditor').find('.cke_show_borders').eq(0).clone();
console.log(content.get(0).outerHTML);
'outerHTML' working for me.
In Google Tag Manager 'custom javasctipt' part {{Click Element}} returns [object HTMLElement].
function() {
var elm = {{Click Element}};
return elm.outerHTML; // working
}
Result -
<i _ngcontent-c1="" class="material-icons">edit</i>
You can use content.innerHTML This will solve your issue

jade (for nodejs) substrings in templates

Would anyone please advise how in jade for nodejs I can truncate a string to a number of characters/words, ideally conscious about the HTML markup within the string?
This should be similar to Django's truncatechars/truncatewords and truncatechars_html/truncatewords_html filters.
If this doesn't exist in jade, which way is right to go? I'm starting my first nodejs+express+CouchDB app, and could do it within nodejs code but it seems that filters are much more appropriate.
I would also consider writing a filter like this (and others) if I knew how :))
Just a quick illustration:
// in nodejs:
// body variable comes from CouchDB
res.render('home.jade', { title : "test", featuredNews : eval(body)});
// in home.jade template:
ul.thumbnails
each article in featuredNews.rows
a(href="#"+article.slug)
li.span4
div.value.thumbnail
img(align='left',src='http://example.com/image.png')
p!= article.value.description:truncatewords_html(30)
So I've made up the truncatewords_html(30) thing to illustrate what I think it should be similar to.
Will appreciate any ideas!
Thanks,
Igor
Here is a little "truncate_words" function:
function truncate( value, arg ) {
var value_arr = value.split( ' ' );
if( arg < value_arr.length ) {
value = value_arr.slice( 0, arg ).join( ' ' );
}
return value;
}
You can use it before sending the string to the template, or in the template using a helper method.
cheerio is a nice little library that does a subset of jquery and jsdom. Then it's easy:
app.helpers({
truncateWords_html : function(html, words){
return cheerio(html).text().split(/\s/).slice(0, words).join(" ")
}
})
Then, in a jade template use:
#{truncateWords_html(article.value.description, 30)}
This looks like a generic way to add any filters, hurray! :))

How do you deal with the fact, that URLs are case sensitive in xPages?

How do you deal with the fact, that URLs are case sensitive in xPages even for parameters? For example URL:
my_page.xsp?folderid=785478 ... is not the same as ...
my_page.xsp?FOLDERID=785478
How to make, for example, a proper check that params contain some key e.g.
param.containsKey("folderid") which desnt work when there is 'FOLDERID' in URL.
I'd suggest defining a couple convenience #Functions:
var #HasParam = function(parameter) {
var result:boolean = false;
for (var eachParam : param.keySet()) {
if (eachParam.toLowerCase() == parameter.toLowerCase()) {
result = true;
break;
}
}
return result;
};
var #GetParam = function(parameter) {
var result = "";
if (#HasParam(parameter)) {
for (var eachParam : param.keySet()) {
if (eachParam.toLowerCase() == parameter.toLowerCase()) {
result = param.get(eachParam);
break;
}
}
}
return result;
};
Then you can safely query the parameters without caring about case. For bonus points, you could add requestScope caching so that you can skip looping through the keySet if you're examining a parameter that you've previously looked at during the same request.
you may use this function:
context.getUrlParameter('param_name')
then test if it's null or not.
make sure to decide for one,so either upper or lowercase
other than that i'd suggest something like
KeyValuePair<string,string> kvp = null;
foreach(KeyValuePair<string,string> p in param)
{
if(UPPERCASE(p.Key) == UPPERCASE("folderid"))
{
kvp = p;
break;
}
}
syntax isn't correct and idk the uppercase method in c# right now,but you get the point
The easiest answer is ofcourse the obvious. Be sure that the parameters you are using througout your application are always the same on every url you are generating and know what to expect. A good approach to accomplish this is to create a ssjs function which generates url's for you according to the objects you submit.
In this function you could check which object you are receiving and with the use of keywords and so forth generate the correct url. This way generating twice a url with the same input parameters should always generate the exact same url.
another option would be just to double check with a bit of code like this
var key = "yourkey";
if(param.contains(#uppercase(key)) || param.contains(#lowercase(key)){
// do stuff
}
But should not be necesarry if the url you are parsing is generated by your own application
Edit after post of topic starter
Another option would be to grap the url directly from from the facescontext and to convert it to a string first. When it is a string you can parse the parameters yourself.
You can combine server side substitution/redirection to get around the issue that David mentioned. So a substitution rule will redirect incoming patern like this:
http://myhost/mypage/param (/mypage/* => which converts to - /dbpath/mypage.xsp?*) - substitution is tricky so please handle with care.
Also I believe I read somewhere that context.getUrlParameter is not case sensitive - can someone please confirm this.
Hope this helps.

Resources