Sync gateway function not filtering documents


#1

I am inserting documents in couchbase server using sync gateway. But my sync gateway is not filtering instead it is putting all documents in the couchbase server

Below is the android app code

package com.couchbase.examples.couchbaseevents;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;

import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.replicator.Replication;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    public static final String DB_NAME = "couchbaseevents";
    final String TAG = "CouchbaseEvents";
    Database database = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	Log.d(TAG, "Begin Couchbase Events App");
	Manager manager = null;
	try {
	    manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
	    database = manager.getDatabase(DB_NAME);
	} catch (Exception e) {
	    Log.d(TAG, "Error getting database", e);
	    return;
	}
	/*try {
	    database.delete();
	} catch (Exception e) {
	    Log.e(TAG, "Cannot delete database", e);
	    return;
	}*/
     /*   Document createdDocument = createDocument(database);
	Log.d(TAG, "createdDocument=" + String.valueOf(createdDocument.getProperties()));
      /*  // retrieve the document from the database
	Document retrievedDocument = database.getDocument(createdDocument.getId());
// display the retrieved document
	Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
	updateDoc(database, createdDocument.getId());
	Document updatedDocument = database.getDocument(createdDocument.getId());
	Log.d(TAG, "updatedDocument=" + String.valueOf(updatedDocument.getProperties()));*/
	try {
	    startReplications();
	} catch (CouchbaseLiteException e) {
	    e.printStackTrace();
	}
	Document retrievedDocument = database.getDocument("af4e5155-27a6-4d24-89d2-76aace253683");
// display the retrieved document
	Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
	Log.d(TAG, "End Couchbase Events App");
    }
    private void updateDoc(Database database, String documentId) {
	Document document = database.getDocument(documentId);
	try {
	    // Update the document with more data
	    Map<String, Object> updatedProperties = new HashMap<String, Object>();
	    updatedProperties.putAll(document.getProperties());
	    updatedProperties.put("eventDescription", "Everyone is invited!");
	    updatedProperties.put("address", "123 Elm St.");
	    // Save to the Couchbase local Couchbase Lite DB
	    document.putProperties(updatedProperties);
	} catch (CouchbaseLiteException e) {
	    Log.e(TAG, "Error putting", e);
	}
    }
    private Document createDocument(Database database) {
	// Create a new document and add data
	Document document = database.createDocument();
	String documentId = document.getId();
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("name", "Big Party");
	map.put("location", "My House");
	try {
	    // Save the properties to the document
	    document.putProperties(map);
	} catch (CouchbaseLiteException e) {
	    Log.e(TAG, "Error putting", e);
	}
	Document document1 = database.createDocument();
	documentId = document1.getId();
	Map<String, Object> map1 = new HashMap<String, Object>();
	map1.put("name", "Yagyank");
	map1.put("location", "GGn");
	try {
	    // Save the properties to the document
	    document1.putProperties(map1);
	} catch (CouchbaseLiteException e) {
	    Log.e(TAG, "Error putting", e);
	}
	Document document2 = database.createDocument();
	documentId = document2.getId();
	Map<String, Object> map2 = new HashMap<String, Object>();
	map2.put("name", "Farheen");
	map2.put("location", "GGn");
	try {
	    // Save the properties to the document
	    document2.putProperties(map2);
	} catch (CouchbaseLiteException e) {
	    Log.e(TAG, "Error putting", e);
	}
	return document;
    }
    private URL createSyncURL(boolean isEncrypted){
	URL syncURL = null;
	String host = "http://172.16.25.100";
	String port = "4986";
	String dbName = "sync_gateway";
	try {
	    //syncURL = new URL("http://127.0.0.1   :4986/sync_gateway");
	    syncURL = new URL(host + ":" + port + "/" + dbName);
	} catch (Exception me) {
	    me.printStackTrace();
	}
	Log.d(syncURL.toString(),"URL");
	return syncURL;
    }
    private void startReplications() throws CouchbaseLiteException {
	Replication pull = database.createPullReplication(this.createSyncURL(false));
	Replication push = database.createPushReplication(this.createSyncURL(false));
	pull.setContinuous(true);
	push.setContinuous(true);
	pull.start();
	push.start();
	if(!push.isRunning()){
	    Log.d(TAG, "MyBad");
	}
	/*if(!push.isRunning()) {
	    Log.d(TAG, "Replication is not running due to " +push.getLastError().getMessage());
	    Log.d(TAG, "Replication is not running due to " +push.getLastError().getCause());
	    Log.d(TAG, "Replication is not running due to " +push.getLastError().getStackTrace());
	    Log.d(TAG, "Replication is not running due to " +push.getLastError().toString());
	}*/
    }

}

Below is the sync gateway config file

{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
	"interface":":4986",
   "adminInterface":":14985",
    "databases": {
	"sync_gateway": {
	    "server":"http://127.0.0.1:8091",
	    "bucket":"sync_gateway",
	    "sync":`
	        function (doc) {
		if(!doc.name){
			return
			}
		channel (doc.channels);
	    }`,
	    "users": {
	        "GUEST": {
	            "disabled": false,
	            "admin_channels": ["*"]
	        }
	    }
	}
    }
}

As you can see I am creating three documents in it. Two of them have name field while one of them has not. But in my couchBase server I can see all the three documents being inserted which means my sync gateway’s sync function is not working


#2

@yagyank.chadha

Your sync function will not prevent documents without a name property being written to the bucket, it will only prevent them from being mapped to the channels defined in doc.channels.

To prevent the document being written to the bucket you can call throw() with an error message that will be returned to the client. This is the most basic way to reject a document, there are other sync gateway functions that can also do this.

Here are the [docs](file:///Users/andy/Projects/couchbase-mobile-portal/site/gen/develop/guides/sync-gateway/sync-function-api-guide/validation/index.html)


#6

@Andy Thank you it helped :slight_smile: Can you tell me whether we can make sync function dynamic? or not?