Below are some sample records stored in couchbase:
{
a: "iama",
b: {
c: "iamc",
d: "iamd",
},
f: "iamf"
// ... other properties that are not relevant
}
{
a: "iama",
b: {
c: "iamc",
d: "iamd"
},
f: "iamnotf"
// ... other properties that are not relevant
}
I need to retrieve records where the entire object of b
matches, without knowing the exact contents of b.
I am using ottomanjs and have attempted the following code. However, I believe it is not very elegant.
const arr = [];
Object.keys(b).forEach((key) => {
const k = `b.${key}`;
arr.push({ [k]: b[key] });
});
model.find({ $and: arr });
In the example above, the generated filter looks like this:
{
"$and": [
{
"b.c": "iamc"
},
{
"b.d": "iamd"
}
]
}
This filter will be converted into an N1QL query like so:
SELECT * FROM `table` WHERE ( b.c="iamc" AND b.d="iamd") AND _type="model..."
This method only covers the scenario where every property of b is not a nested object. To handle nested objects, a recursive function could be implemented for constructing the filter.
Another approach could involve processing everything in memory by comparing
JSON.stringify(b1) == JSON.stringfy(b2)
or using _.isEqual(b1, b2)
I suspect that my current solution may not be the most efficient. Any advice or alternative approaches?
**other info
If I require all records to have a unique b field, I could use the stringified version of b as the document key. This way, searching for b would simply involve looking up the document id. While ottoman does not support this feature, it can be accomplished with the couchbase sdk.