www.webdeveloper.com
Results 1 to 3 of 3

Thread: Where am I going wrong with this javascript?

  1. #1
    Join Date
    Mar 2013
    Posts
    2

    Where am I going wrong with this javascript?

    I'm using javascript in CouchDb to build a filter which takes arguments. In the filter I'm trying to retrieve an array in CouchDB and see if it contains a parameter I pass in. I know the data going in is fine, and the function works fine without this code: `(countries.indexOf(rec.query.country) != -1)` I can't figure out what's going on. The complete function looks like:

    function (doc, rec) {

    if (doc.expiryDate == null && (doc.countries.indexOf(rec.query.country) != -1)) {
    return doc;
    } else {
    var expiry = doc.expiryDate;
    if (expiry > rec.query.today && (doc.countries.indexOf(rec.query.country) != -1)) {
    return doc;
    }
    }}


    JSON for countries inside the document looks like:

    "countries": [
    "GB",
    "US"],


    The query:

    http://myaccount.iriscouch.com/mydb/...-30&country=GB

    Any ideas? I'm convinced `doc.countries` is the problem but have no idea how to successfully iterate on it and check its contents?

  2. #2
    Join Date
    Mar 2013
    Posts
    2
    Code:
    function (doc, rec) {
    
    if (doc.expiryDate == null && (doc.countries.indexOf(rec.query.country) != -1)) {
       return doc;
    } else {
       var expiry = doc.expiryDate;
       if (expiry > rec.query.today && (doc.countries.indexOf(rec.query.country) != -1)) {
            return doc;
       }
    }}

  3. #3
    Join Date
    Dec 2012
    Posts
    5
    1st of all I tried
    var doc = {"countries": ["GB","US"]};

    console.log(doc.countries.indexOf('US') != -1);
    returns true

    console.log(doc.countries.indexOf('A') != -1);
    returns fasle

    so.. there is nothing wrong with the iteration.That means the problem isn't there.If I were you, I would do:
    Code:
    function (doc, rec) {
    
    console.log("looking for" + rec.query.country + " in " + doc.countries);
    if(doc.countries.indexOf(rec.query.country) != -1){
        console.log("country exists in doc.countries and by the way doc.expiryDate = "+doc.expiryDate);
        if (doc.expiryDate == null ) {
            return doc;
        } else {
            var expiry = doc.expiryDate;
            if (expiry > rec.query.today) {
                return doc;
            }
        }
    }
    }
    Since you have the same condition both times why not just ask for it in the begining. Always avoid dublication of code.
    Check the results in your console.I hope this will help you see where your problem come from.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles