Chaincode can't find index - couchdb

I'm trying to query the data from CouchDB and have made an index to be able to sort the data.
But no matter what I try, I always get the following error:
Error: GET_QUERY_RESULT failed, No index exists for this sort, try indexing by the sort fields
I have put the index in the META_INF/statedb/couchdb/indexes dir and according the logs is the index successfully created.
This is my query string:
var queryString = {};
queryString.selector = {};
queryString.selector.docType = docType;
queryString.selector.assetId = {"$gt" : null};
queryString.sort= [{assetId : "desc"}];
queryString.limit = 1;
queryString.use_index = ["_design/indexAssetIdDoc" , "indexAssetId"];
and this is the index:
{
"index":
{
"fields":["docType","assetId"]
},
"ddoc":"indexAssetIdDoc",
"name":"indexAssetId",
"type":"json"
}
when using the query and index in the couchdb webapplication is works perfectly.
pictures:
index creation
error

Related

Error in returning new value from Mongoose Database (Nodejs)

When I execute a find query in mongodb after executing a findOneAndUpdate query the data that is returned is not the updated one eventhough the data has been correctly updated in the database.
I find the list of all entries which have a particular code/codes,
let codeList:Array<CodeBase> = await codebaseModel.find({codeBaseId: codes});
I loop through each entry and where the fileTree needs to be updated, I get the directory tree and update it
if (codeList.length > 0) {
codeList.forEach( (e): void => {
if (e.fileTree === 'To be updated') {
let tree = directoryTree(src/uploads/${e.codeBaseId}/unzipped/);
let treeData = JSON.stringify(tree);
let value = codebaseModel.findOneAndUpdate(
{ codeBaseId: e.codeBaseId },
{ fileTree: treeData },
{ upsert:true,new:true, }
);
}
});
}
I need get the updated list again (so as to ensure that I have the entries with the updated fileTree values.
let codeListNext:Array<CodeBase> | null | void = [];
await codebaseModel.find({
codeBaseId: codes,
},).then((value:Array<CodeBase>)=>{
codeListNext = value;
});
console.log(Firstlist length is ${codeListNext});
However, the list that is returned is the old list. However, the mongodb database has updated values. I tried using async await but was not successful. Can someone help me understand where am I going wrong ?

Mongoose, NodeJS & Express: Sorting by column given by api call

I'm currently writing a small API for a cooking app. I have a Recipe model and would like to implement sorting by columns based on the req Parameter given.
I'd like to sort by whatever is passed in the api call. the select parameter works perfectly fine, I can select the columns to be displayed but when I try to sort anything (let's say by rating) the return does sort but I'm not sure what it does sort by.
The code i'm using:
query = Recipe.find(JSON.parse(queryStr));
if(req.query.select){
const fields = req.query.select.split(',').join(' ');
query = query.select(fields);
}
if(req.query.sort){
const sortBy = req.query.sort.split(',').join(' ');
query = query.sort({ sortBy: 1 });
} else {
query = query.sort({ _id: -1 });
}
The result, when no sorting is set: https://pastebin.com/rPLv8n5s
vs. the result when I pass &sort=rating: https://pastebin.com/7eYwAvQf
also, when sorting my name the result is also mixed up.
You are not using the value of sortBy but the string "sortBy". You will need to create an object that has the rating as an object key.
You need the sorting object to look like this.
{
rating: 1
}
You can use something like this so it will be dynamic.
if(req.query.sort){
const sortByKey = req.query.sort.split(',').join(' ');
const sortByObj = {};
sortByObj[sortByKey] = 1; // <-- using sortBy as the key
query = query.sort(sortByObj);
} else {
query = query.sort({ _id: -1 });
}

Cosmos DB: range string index return query error

I'm trying to create custom index policy on CosmosDB documents collection for include only 1 field in index.
The index policy looks like :
new IndexingPolicy
{
Automatic = true,
IndexingMode = IndexingMode.Consistent,
ExcludedPaths = new Collection<ExcludedPath>(new[]
{
new ExcludedPath { Path = "/*" }
}),
IncludedPaths = new Collection<IncludedPath>(new[]
{
new IncludedPath
{
Path = "/Id/?",
Indexes = new Collection<Index>(new Index[] { new RangeIndex(DataType.String) {Precision = -1 } })
}
})
};
Then I do query on documents collection :
CosmosClient.CreateDocumentQuery<Entity>(
CollectionUri(docCollection),
"SELECT x from x where x.Id != \"\" ",
new FeedOptions
{
MaxItemCount = 100,
RequestContinuation = null,
EnableCrossPartitionQuery = false,
PartitionKey = new PartitionKey("entities"),
}).AsDocumentQuery();
Such request throws an error: An invalid query has been specified with filters against path(s) excluded from indexing. Consider adding allow scan header in the request.
While almost same one (check for equality instead of unequality) gives correct result.
Did I configure index policy wrong or I need to specify some additional args when querying? Thanks
Your partition key path should also be included in the included paths. It's implicitly included as a filter because you're setting it in PartitionKey = new PartitionKey("entities").

Getting error "pipeline element 3 is not an object error", while trying to find & update using aggregate

I am using node js mongodb driver & trying to update an object array inside an object array in a document.
The schema of the document collection is this :
What I Want :
For collection with order no = 1 & items.qty=2 & tax rate = 25, update the tax to "cst" & taxratetype to "flat".
What I Tried :
db.OrderInfo.aggregate(
{$match:{"orderno":"1"}},
{$unwind:'$items'},
{ $match: { 'items.qty' : 2}
},function(err,result1){
if(err){
throw(err);
}else{
indexes = result1[0].items.taxes.map(function(obj, index) {
if(obj.taxrate == 25) {
return index;
}
}).filter(isFinite);
var updateData = {};
updateData["items.$.taxes."+indexes[0]+".tax"]="cst";
updateData["items.$.taxes."+indexes[0]+".taxratetype"]="flat";
db.OrderInfo.update({ "orderno":"1",'items.qty': 2,'items.taxes.taxrate': 25 },{$set: updateData },function(err,result2){
console.log(result2);
});
}
});
Currently I am using db.eval to run this script from node but later will change it once I accomplish the same.
Getting this Error :
{"name":"MongoError","message":"Error: command failed: {\n\t\"ok\" :
0,\n\t\"errmsg\" : \"pipeline element 3 is not an
object\",\n\t\"code\" : 15942\n} : aggregate failed
:\n_getErrorWithCode#src/mongo/shell/utils.js:25:13\ndoassert#src/mongo/shell/assert.js:13:14\nassert.commandWorked#src/mongo/shell/assert.js:267:5\nDBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5\n_funcs1#:1:31\n","ok":0,"errmsg":"Error:
command failed: {\n\t\"ok\" : 0,\n\t\"errmsg\" : \"pipeline element 3
is not an object\",\n\t\"code\" : 15942\n} : aggregate failed
:\n_getErrorWithCode#src/mongo/shell/utils.js:25:13\ndoassert#src/mongo/shell/assert.js:13:14\nassert.commandWorked#src/mongo/shell/assert.js:267:5\nDBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5\n_funcs1#:1:31\n","code":139}
I know from this issue https://jira.mongodb.org/browse/SERVER-831
that I cannot use a direct update command & hence trying this workaround.
Any other approach for such updates is also fine with me.
EDIT :
As per answer given by #titi23, I had tried using [] also inside function.
It did not gave me any error but, my values also did not get updated.
Two problems in the query :
1) You are missing [] in the aggregate query.
2) The update method does not need the tax rate clause. It will find the nested document & the index from aggregate would serve the purpose in update.
Refer aggregate-definition for more info on how to use it.
Syntax - db.collection.aggregate(pipeline, options)
pipeline - array - A sequence of data aggregation operations or stages.
Try the following:-
db.OrderInfo.aggregate([
{$match:{"orderno":"1"}},
{$unwind:'$items'},
{ $match: { 'items.qty' : 2} }]).toArray(
function(err,result1){
if(err){
throw(err);
}
else{
console.log(result[0]); //See is there any record here
indexes = result1[0].items.taxes.map(function(obj, index) {
if(obj.taxrate == 25) {
return index;
}
}).filter(isFinite);
var updateData = {};
updateData["items.$.taxes."+indexes[0]+".tax"]="cst";
updateData["items.$.taxes."+indexes[0]+".taxratetype"]="flat";
db.OrderInfo.update({ "orderno":"1",'items.qty': 2}, /*Remove the tax rate clause from here..*/
{$set: updateData },function(err,result2){
console.log(result2);
});
}
});
It should not throw the error.
EDIT:- Do toArray() with the aggregate, see if it helps. Updated the query already.

using $exists in Mongo with dynamic key names and the native driver for node

I have a document in a collection like so:
{
container : {
P39433: 2,
P30213: 4
}
}
The values 'P39433' and 'P30213' are dynamically generated in the program. I can run the following query using the dot notation against mongo directly and I get the desired result
db.collection.findOne({ "container.P00000" : { $exists : false } })
I get the document back. i.e. I only want to get the document if the field does not exist.
My question is how can I run that query in Node using the native driver when the value P00000
is contained in a variable.
My usual solution is to structure the query like below but it does not return a result.
var fieldName = 'P00000';
var dynObj = {};
dynObj[fieldName] = { $exists : false };
db.collection.findOne( { "container" : dynObj });
You're close. Try this:
var fieldName = 'P00000';
var dynObj = {};
dynObj["container." + fieldName] = { $exists: false };
db.collection.findOne(dynObj);
Update
Now that Node.js 4+ supports computed property names, you can create dynObj in one step as:
var dynObj = {
["container." + fieldName]: { $exists: false }
};

Resources