UI Router query parameters and multiple states - search

I've been trying to get my head around query parameters with UI Router and think I have finally figured out why I'm having such a hard time with it. I'm building a small search app that has 2 states:
$stateProvider
.state('home', {
url: '/',
.state('search', {
url: '/search',
},
The home state has its own template (view) and so does the search state. They share the same controller. Basically all home state does is provide a search box to enter your search query or choose from autocomplete.
Once you have submitted your search query it goes to the search state via
$state.go('search');
I've tried many ways to get the user's search term(s) in the url on the search page using UI Router's query parameter syntax in the url: '/search?q' combined with $stateParams in the controller set as
vm.searchTerms = $stateParams.q || '';
I had switched it to $state.params.q but that didn't fix it.
I have successfully been able to get the query parameters in the url, however, when I do, it breaks search functionality. The autocomplete and query parameters work and display, but search function stops.
However, I think I finally understand why its not working the way I'd like it to. I believe it has to do with the fact that I'm using 2 states and not one parent state with a nested child state and that the templates are not nested - so $scope doesn't inherit. I'm getting close to this working... it transitions from the home state to the search state displaying query parameters in the search state's url... its simply that search breaks, but autocomplete and query parameters are working.
What I'm trying to achieve is to have the user enter search terms from the home state and then have results display in the search state along with query parameters in the url. Is there anything I need to do with home state or search state that I'm not doing?
OR
Is there anything in my search() in my controller that could be the problem
//search()
vm.search = function() {
//$state.go('search', {q: vm.searchTerms});
$state.go('search');
console.log(vm.searchTerms);
console.log('success - search');
vm.currentPage = 1;
vm.results.documents = [];
vm.isSearching = true;
return coreService.search(vm.searchTerms, vm.currentPage)
.then(function(es_return) {
console.log('success - return');
var totalItems = es_return.hits.total;
var totalTime = es_return.took;
var numPages = Math.ceil(es_return.hits.total / vm.itemsPerPage);
vm.results.pagination = [];
for (var i = 0; i <= 10; i++) {
console.log('success - for');
vm.results.totalItems = totalItems;
vm.results.queryTime = totalTime;
vm.results.pagination = coreService.formatResults(es_return.hits.hits);
vm.results.documents = vm.results.pagination.slice(vm.currentPage, vm.itemsPerPage);
console.log('success - documents');
}
vm.noResults = true;
}),
function(error){
console.log('ERROR: ', error.message);
vm.isSearching = false;
},
vm.captureQuery();
console.log('success - captureQuery');
};

You can add a parameter to your URL in two ways, use colon:
'url': '/search/:query'
or curly braces:
'url': '/search/{query}'
Then you can use the go method of $state with parameter to transition:
$state.go('search', {'query', 'foobar'});
You can access the parameter's value from your controller by using the params member of your $state object:
console.log($state.params.query);
or directly from the $stateParams object:
console.log($stateParams.query);
Reference: https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters

Related

setting context with list of objects as prameters in dialogflow

I have a list of values each having another KEY value corresponding to it, when i present this list to user, user has to select a value and agent has to call an external api with selected value's KEY. how can i achieve this in dialogflow?
I tried to send the entire key value pair in the context and access it in the next intent but for some reason when i set a list(array) to context parameters dialogflow simply ignoring the fulfillment response.
What is happening here and is there any good way to achieve this? I am trying to develop a food ordering chatbot where the category of items in menu is presented and list items in that menu will fetched when user selects a category, this menu is not static thats why i am using api calls to get the dynamic menu.
function newOrder(agent)
{
var categories = []
var cat_parameters = {}
var catarray = []
const conv = agent.conv();
//conv.ask('sure, select a category to order');
agent.add('select a category to order');
return getAllCategories().then((result)=>{
for(let i=0; i< result.restuarantMenuList.length; i++)
{
try{
var name = result.restuarantMenuList[i].Name;
var catid = result.restuarantMenuList[i].Id;
categories.push(name)
//categories.name = catid
cat_parameters['id'] = catid;
cat_parameters['name'] = name
catarray.push(cat_parameters)
}catch(ex)
{
agent.add('trouble getting the list please try again later')
}
}
agent.context.set({
name: 'categorynames',
lifespan: 5,
parameters: catarray, // if i omit this line, the reponse is the fultillment response with categories names, if i keep this line the reponse is fetching from default static console one.
})
return agent.add('\n'+categories.toString())
})
function selectedCategory(agent)
{
//agent.add('category items should be fetched and displayed here');
var cat = agent.parameters.category
const categories = agent.context.get('categorynames')
const cat_ob = categories.parameters.cat_parameters
// use the key in the catarray with the parameter cat to call the external API
agent.add('you have selected '+ cat );
}
}
The primary issue is that the context parameters must be an object, it cannot be an array.
So when you save it, you can do something like
parameters: {
"cat_parameters": catarray
}
and when you deal with it when you get the reply, you can get the array back with
let catarray = categories.parameters.cat_parameters;
(There are some other syntax and scoping issues with your code, but this seems like it is the data availability issue you're having.)

React Native: Reach-Navigation and Pouch-DB - db.put not done before "refresh" callback is run

Relative newbie; forgive me if my etiquette and form here aren't great. I'm open to feedback.
I have used create-react-native-app to create an application using PouchDB (which I believe ultimately uses AsyncStorage) to store a list of "items" (basically).
Within a TabNavigator (main app) I have a StackNavigator ("List screen") for the relevant portion of the app. It looks to the DB and queries for the items and then I .map() over each returned record to generate custom ListView-like components dynamically. If there are no records, it alternately displays a prompt telling the user so. In either case, there is an "Add Item" TouchableOpacity that takes them to a screen where they an add a new item (for which they are taken to an "Add" screen).
When navigating back from the "Add" screen I'm using a pattern discussed quite a bit here on SO in which I've passed a "refresh" function as a navigation param. Once the user uses a button on the "Add" screen to "save" the changes, it then does a db.post() and adds them item, runs the "refresh" function on the "List screen" and then navigates back like so:
<TouchableOpacity
style={styles.myButton}
onPress={() => {
if (this.state.itemBrand == '') {
Alert.alert(
'Missing Information',
'Please be sure to select a Brand',
[
{text: 'OK', onPress: () =>
console.log('OK pressed on AddItemScreen')},
],
{ cancelable: false }
)
} else {
this.createItem();
this.props.navigation.state.params.onGoBack();
this.props.navigation.navigate('ItemsScreen');
}
}
}
>
And all of this works fine. The "refresh" function (passed as onGoBack param) works fine... for this screen. The database is called with the query, the new entry is found and the components for the item renders up like a charm.
Each of the rendered ListItem-like components on the "List screen" contains a react-native-slideout with an "Edit" option. An onPress for these will send the user to an "Item Details" screen, and the selected item's _id from PouchDB is passed as a prop to the "Item Details" screen where loadItem() runs in componentDidMount and does a db.get(id) in the database module. Additional details are shown from a list of "events" property for that _id (which are objects, in an array) which render out into another bunch of ListItem-like components.
The problem arises when either choose to "Add" an event to the list for the item... or Delete it (using another function via [another] slideout for these items. There is a similar backward navigation, called in the same form as above after either of the two functions is called from the "Add Event" screen, this being the "Add" example:
async createEvent() {
var eventData = {
eventName: this.state.eventName.trim(),
eventSponsor: this.state.eventSponsor.trim(),
eventDate: this.state.eventDate,
eventJudge: this.state.eventJudge.trim(),
eventStandings: this.state.eventStandings.trim(),
eventPointsEarned: parseInt(this.state.eventPointsEarned.trim()),
};
var key = this.key;
var rev = this.rev;
await db.createEvent(key, rev, eventData);
}
which calls my "db_ops" module function:
exports.createEvent = function (id, rev, eventData) {
console.log('You called db.createEvent()');
db.get(id)
.then(function(doc) {
var arrWork = doc.events; //assign array of events to working variable
console.log('arrWork is first assigned: ' + arrWork);
arrWork.push(eventData);
console.log('then, arrWork was pushed and became: ' + arrWork);
var arrEvents = arrWork.sort((a,b)=>{
var dateA = new Date(a.eventDate), dateB = new Date(b.eventDate);
return b.eventDate - a.eventDate;
})
doc.events = arrEvents;
return db.put(doc);
})
.then((response) => {
console.log("db.createEvent() response was:\n" +
JSON.stringify(response));
})
.catch(function(err){
console.log("Error in db.createEvent():\n" + err);
});
}
After which the "Add Event" screen's button fires the above in similar sequence to the first, just before navigating back:
this.createEvent();
this.props.navigation.state.params.onGoBack();
this.props.navigation.navigate('ItemsDetails');
The "refresh" function looks like so (also called in componentDidMount):
loadItem() {
console.log('Someone called loadItem() with this.itemID of ' + this.itemID);
var id = this.itemID;
let totalWon = 0;
db.loadItem(id)
.then((item) => {
console.log('[LOAD ITEM] got back data of:\n' + JSON.stringify(item));
this.setState({objItem: item, events: item.events});
if (this.state.events.length != 0) { this.setState({itemLoaded: true});
this.state.events.map(function(event) {
totalWon += parseInt(event.eventPointsEarned);
console.log('totalWon is ' + totalWon + ' with ' +
event.eventPointsEarned + ' having been added.');
});
};
this.setState({totalWon: totalWon});
})
.catch((err) => {
console.log('db.loadItem() error: ' + err);
this.setState({itemLoaded: false});
});
}
I'm at a loss for why the List Screen refreshes when I add an item... but not when I'm doing other async db operations with PouchDB in what I think is similar fashion to modify the object containing the "event" information and then heading back to the Item Details screen.
Am I screwing up with Promise chain someplace? Neglecting behavior of the StackNavigator when navigating deeper?
The only other difference being that I'm manipulating the array in the db function in the non-working case, whereas the others I'm merely creating/posting or deleting/removing the record, etc. before going back to update state on the prior screen.
Edit to add, as per comments, going back to "List screen" and the opening "Item Details" does pull the database data and correctly shows that the update was made.
Further checking I've done also revealed that the console.log in createEvent() to print the response to the db call isn't logging until after some of the other dynamic rendering methods are getting called on the "Item Details" screen. So it seems as though the prior screen is doing the get() that loadItem() calls before the Promise chain in createEvent() is resolving. Whether the larger issue is due to state management is still unclear -- though it would make sense in some respects -- to me as this could be happening regardless of whether I've called my onGoBack() function.
Edit/bump: I’ve tried to put async/await to use in various places in both the db_ops module on the db.get() and the component-side loadItem() which calls it. There’s something in the timing of these that just doesn’t jive and I am just totally stuck here. Aside from trying out redux (which I think is overkill in this particular case), any ideas?
There is nothing to do with PDB or navigation, it's about how you manage outer changes in your depending (already mounted in Navigator since they are in history - it's important to understand - so componentDidMount isn't enough) components. If you don't use global state redux-alike management (as I do) the only way to let know depending component that it should update is passing corresponding props and checking if they were changed.
Like so:
//root.js
refreshEvents = ()=> { //pass it to DeleteView via screenProps
this.setState({time2refreshEvents: +new Date()}) //pass time2refreshEvents to EventList via screenProps
}
//DeleteView.js
//delete button...
onPress={db.deleteThing(thingID).then(()=> this.props.screenProps.refreshEvents())}
//EventList.js
...
constructor(props) {
super(props);
this.state = {
events: [],
noEvents: false,
ready: false,
time2refreshEvents: this.props.screenProps.time2refreshEvents,
}
}
static getDerivedStateFromProps(nextProps, currentState) {
if (nextProps.screenProps.time2refreshEvents !== currentState.time2refreshEvents ) {
return {time2refreshEvents : nextProps.screenProps.time2refreshEvents }
} else {
return null
}
}
componentDidMount() {
this._getEvents()
}
componentDidUpdate(prevProps, prevState) {
if (this.state.time2refreshEvents !== prevState.time2refreshEvents) {
this._getEvents()
}
}
_getEvents = ()=> {
//do stuff querying db and updating your list with actual data
}

How to provide custom names for page view events in Azure App Insights?

By default App Insights use page title as event name. Having dynamic page names, like "Order 32424", creates insane amount of event types.
Documentation on the matter says to use trackEvent method, but there are no examples.
appInsights.trackEvent("Edit button clicked", { "Source URL": "http://www.contoso.com/index" })
What is the best approach? It would be perfect to have some sort of map/filter which would allow to modify event name for some pages to the shared name, like "Order 23424" => "Order", at the same time to leave most pages as they are.
You should be able to leverage telemetry initializer approach to replace certain pattern in the event name with the more "common" version of that name.
Here is the example from Application Insights JS SDK GitHub on how to modify pageView's data before it's sent out. With the slight modification you may use it to change event names based on their appearance:
window.appInsights = appInsights;
...
// Add telemetry initializer
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(function (envelope) {
var telemetryItem = envelope.data.baseData;
// To check the telemetry item’s type:
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) {
// this statement removes url from all page view documents
telemetryItem.url = "URL CENSORED";
}
// To set custom properties:
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["globalProperty"] = "boo";
// To set custom metrics:
telemetryItem.measurements = telemetryItem.measurements || {};
telemetryItem.measurements["globalMetric"] = 100;
});
});
// end
...
appInsights.trackPageView();
appInsights.trackEvent(...);
With help of Dmitry Matveev I've came with the following final code:
var appInsights = window.appInsights;
if (appInsights && appInsights.queue) {
function adjustPageName(item) {
var name = item.name.replace("AppName", "");
if (name.indexOf("Order") !== -1)
return "Order";
if (name.indexOf("Product") !== -1)
return "Shop";
// And so on...
return name;
}
// Add telemetry initializer
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(function (envelope) {
var telemetryItem = envelope.data.baseData;
// To check the telemetry item’s type:
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType || envelope.name === Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType) {
// Do not track admin pages
if (telemetryItem.name.indexOf("Admin") !== -1)
return false;
telemetryItem.name = adjustPageName(telemetryItem);
}
});
});
}
Why this code is important? Because App Insights use page titles by default as Name for PageView, so you would have hundreds and thousands of different events, like "Order 123132" which would make further analysis (funnel, flows, events) meaningless.
Key highlights:
var name = item.name.replace("AppName", ""); If you put your App/Product name in title, you probably want to remove it from you event name, because it would just repeat itself everywhere.
appInsights && appInsights.queue you should check for appInsights.queue because for some reason it can be not defined and it would cause an error.
if (telemetryItem.name.indexOf("Admin") !== -1) return false; returning false will cause event to be not recorded at all. There certain events/pages you most likely do not want to track, like admin part of website.
There are two types of events which use page title as event name: PageView
and PageViewPerformance. It makes sense to modify both of them.
Here's one work-around, if you're using templates to render your /orders/12345 pages:
appInsights.trackPageView({name: TEMPLATE_NAME });
Another option, perhaps better suited for a SPA with react-router:
const Tracker = () => {
let {pathname} = useLocation();
pathname = pathname.replace(/([/]orders[/])([^/]+), "$1*"); // handle /orders/NN/whatever
pathname = pathname.replace(/([/]foo[/]bar[/])([^/]+)(.*)/, "$1*"); // handle /foo/bar/NN/whatever
useEffect(() => {
appInsights.trackPageView({uri: pathname});
}, [pathname]);
return null;
}

CRM 2011 - setting a default value with JScript

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:
function SetDefaultCountryCode(countryFieldId) {
var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
On the form OnLoad I invoke the function like that:
// set Country fields to Canada if not set
SetDefaultCountryCode('cga_address1country');
We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.
I have two questions here:
Is it possible to export / import entity data preserving the GUIDs ?
If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?
Thank you in advance for any help / feedback.
It's very bad practice to hard code your GUIDs and you discovered the problems of it.
As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.
In order to retireve information from client-side (or Entity Form):
We will use/consume REST Endpoint (testing in browser).
Upload jQuery lib.
Upload Json2 lib.
Use the AJAX function from the jQuery library.
Define your entity, columns and criteria.
Lets, look for querying REST Endpoint.
http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'
Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.
After seeing your your results, we are going to call this URL using an AJAX call.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
// now we have the GUID of Canada, now I can continue my process
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
But before you copy the code to your form, you have to download the jQuery lib from here
Then upload it as a Web resource, add this web resource to the Form load libs.
Here is the complete code to be put in the form load event handler:
var context = GetGlobalContext();
// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;
//Retrieve the server url, which differs on-premise from on-line and
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT;
function SetDefaultCountryCode(countryFieldId, odataUri) {
odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
}
One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.
EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.
For more information about the REST Endpoint.
It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.
The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

Retrieving all Documents from couchdb using Node.js

I am writing a simple test app to experiment with the functionality of node.js and couchdb, so far i am loving it, but i ran in a snag. i have looked for and wide but can't seem to find an answer. My test server(a simple address book) does 2 things:
if the user goes to localhost:8000/{id} then my app returns the name and address of the user with that id.
if the user goes to localhost:8000/ then my app needs to return a list a names that are hyperlinks and takes them to the page localhost:8000/{id}.
I was able to get the first requirement working. i cant not seem to find how to retrieve a list of all names from my couchdb. that is what i need help with. here is my code:
var http = require('http');
var cradle = require('cradle');
var conn = new(cradle.Connection)();
var db = conn.database('users');
function getUserByID(id) {
var rv = "";
db.get(id, function(err,doc) {
rv = doc.name;
rv += " lives at " + doc.Address;
});
return rv;
}
function GetAllUsers() {
var rv = ""
return rv;
}
var server = http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/plain'});
var rv = "" ;
var id = req.url.substr(1);
if (id != "")
rv = getUserByID(id);
else
rv = GetAllUsers();
res.end(rv);
});
server.listen(8000);
console.log("server is runnig");
As you can see, I need to fill in the GetAllUsers() function. Any help would be appreciated. Thanks in advance.
I would expect you to be doing something like (using nano, which is a library I authored):
var db = require('nano')('http://localhost:5984/my_db')
, per_page = 10
, params = {include_docs: true, limit: per_page, descending: true}
;
db.list(params, function(error,body,headers) {
console.log(body);
});
I'm not pretty sure what you are trying to accomplish with http over there but feel free to head to my blog if you are looking for some more examples. Just wrote a blog post for people getting started with node and couch
As said above it will come a time when you will need to create your own view. Check up the CouchDB API Wiki, then scan thru the book, check what are design documents, then if you like you can go and check the test code I have for view generation and querying.
You can create a CouchDB view which will list the users. Here are several resources on CouchDB views which you should read in order to get a bigger picture on this topic:
Introduction to CouchDB Views
Finding Your Data with Views
View Cookbook for SQL Jockeys
HTTP View API
So let's say you have documents structured like this:
{
"_id": generated by CouchDB,
"_rev": generated by CouchDB,
"type": "user",
"name": "Johny Bravo",
"isHyperlink": true
}
Then you can create a CouchDB view (the map part) which would look like this:
// view map function definition
function(doc) {
// first check if the doc has type and isHyperlink fields
if(doc.type && doc.isHyperlink) {
// now check if the type is user and isHyperlink is true (this can also inclided in the statement above)
if((doc.type === "user") && (doc.isHyperlink === true)) {
// if the above statements are correct then emit name as it's key and document as value (you can change what is emitted to whatever you want, this is just for example)
emit(doc.name, doc);
}
}
}
When a view is created you can query it from your node.js application:
// query a view
db.view('location of your view', function (err, res) {
// loop through each row returned by the view
res.forEach(function (row) {
// print out to console it's name and isHyperlink flag
console.log(row.name + " - " + row.isHyperlink);
});
});
This is just an example. First I would recommend to go through the resources above and learn the basics of CouchDB views and it's capabilities.

Resources