how to understand mongoDB Api method requirements? - mongodb

i was following along a youtube tutorial video for mongoDB.
the method used was deleteMany from the collection class
and the code was:
function deleteManyItems(MyMongoClient){
var mydb = MyMongoClient.db('school');
var myColl = mydb.collection('students');
myColl.deleteMany(function(error, result){
if(error){
console.log('Sorry unable to delete items');
}else{
console.log(result);
}
})
Although the above code worked,iam a bit confused becasue the official docs for the method say there should be a "filter". And my code worked without the filter:
deleteMany(filter, options, callback)
Delete multiple documents from a collection
lib/collection.js, line 945
My question is how do you know when reading the API documentations what is compulsory and what is not, as it doesn't say in the documentation. is it something you have to figure out by experimenting?

The docs should say which parameters are required. You shouldn't need to guess.
But, they don't as far as I can tell.
Thus, you have to figure out the proper usage the hard way (trial and error or referencing other resources).
Note that in JavaScript, in general:
The language syntax permits invoking any function with any number of parameters. Therefore, in the example you gave, the following invocations would be allowed by the language:
deleteMany()
deleteMany(filter)
deleteMany(filter, options)
deleteMany(filter, options, callback)
deleteMany(filter, options, callback, ignoredParameter)
Despite the language allowing all those invocations, the implementation of the particular method may not. For example, providing 4 parameters like the last example may work the same as providing 3 parameters or it might fail with various errors.
The callback is often the last parameter.
Parameters named options can often be omitted.
If a method accepts a callback, the callback is often allowed to be the last parameter even when it technically violates the documented invocation, for example:
deleteMany(filter, callback)
These conventions don't have to be obeyed by any particular library, therefore they should be documented in the documentation attached to the library.
The documentation for deleteMany states that options is optional but does not state that filter is optional. Therefore, it appears to incorrectly claim that filter is required whereas it really isn't.

Related

Ok, Where is mongoose API about document.save() callback argument?

English is not my first language, but I'm trying hard.
The problem is that I'm using a project using Mongoose, but I can't find a description of the parameter of the callback function in document.save().
genious answer
Official Doc
The link gives me an accurate answer to my question, and the link's the genious who answered explains that there are three things in the callback parameter, but I can't find such an explanation anywhere in the official document, not just an option parameter, Callback parameter
But it's explained as if it's in the official document.
Am I a fool? I want to erase this pathetic question quickly. Help me, Bill Gates.
The guide on how to execute queries mentions the following:
All callbacks in Mongoose use the pattern: callback(error, result). If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.
Since the documentation for Document.prototype.save() says nothing but:
[fn] «Function» optional callback
So you know this function is no exception to the rule. As such, doc.save((err, doc) => { }) is the signature of the callback.

Is it possible to get the type of a variable while computing completion suggestions?

I'm thinking of creating a VSCode extension to help people use a library I am creating. I've looked in 50 places and can only see documentation on getting the plain text of the document in which the completion suggestions are triggered.
My library exposes a function with two parameters, both objects with the same keys, but the first one will be defined already and the 2nd one will be passed in as an object literal. For example
const obj1 = {a:1, b:2};
doLibraryThing(obj1, {a:[], b:[]});
I want to provide code completion, or a snippet, or anything that can detect that doLibraryThing is being called, and know what properties were defined in obj1, even though usually it will be imported from another file; and then use those properties to generate the suggestion with the same properties, {a:[], b:[]}.
Is this possible?

What is the right error code of C_DeriveKey if the derivation key has CKA_DERIVE=0

I am developer of the PKCS#11 library. I think that the function C_DeriveKey should fail with the error code
CKR_KEY_FUNCTION_NOT_PERMITTED
if the key has CKA_DERIVE=0.But this error code is not listed as a possible return value for C_DeriveKey in the specification document . What is the right error code to be returned by C_DeriveKey in this case?
I agree that the specification is not very clear on this case. There is a newer version of the specification available (v3.0 from March 2020, link), but it does not bring more clarity on this. I would make the following considerations:
General note on return values
The introduction on return values in section 5.1 gives the following disclaimer (link):
Because of the complexity of the Cryptoki specification, it is recommended that Cryptoki applications attempt to give some leeway when interpreting Cryptoki functions’ return values. We have attempted to specify the behavior of Cryptoki functions as completely as was feasible; nevertheless, there are presumably some gaps. For example, it is possible that a particular error code which might apply to a particular Cryptoki function is unfortunately not actually listed in the description of that function as a possible error code.
The last part directly acknowledges that the list of possible return values for each function may be incomplete. For that reason, C_DeriveKey not listing CKR_KEY_FUNCTION_NOT_PERMITTED as a possible return code may not be authoritative, if there are other reasons for why the function should return this value.
Definition of the return codes
Section 5.1.6 gives the following definitions (link):
CKR_KEY_FUNCTION_NOT_PERMITTED: An attempt has been made to use a key for a cryptographic purpose that the key’s attributes are not set to allow it to do. For example, to use a key for performing encryption, that key MUST have its CKA_ENCRYPT attribute set to CK_TRUE (the fact that the key MUST have a CKA_ENCRYPT attribute implies that the key cannot be a private key). This return value has lower priority than CKR_KEY_TYPE_INCONSISTENT.
CKR_KEY_TYPE_INCONSISTENT: The specified key is not the correct type of key to use with the specified mechanism. This return value has a higher priority than CKR_KEY_FUNCTION_NOT_PERMITTED.
From this definition I would conclude that CKR_KEY_TYPE_INCONSISTENT is not the right return code for the scenario we are discussing, because it relates the mechanism to the "type" of the key. If we understand "type" in the sense of CKA_KEY_TYPE, it is completely unrelated to the attribute CKA_DERIVE.
Moreover, the attribute CKA_ENCRYPT is given as an example in the definition of CKR_KEY_FUNCTION_NOT_PERMITTED. This attribute is very similar to CKA_DERIVE, i.e. CKA_ENCRYPT controlling whether the key can be used for encryption and CKA_DERIVE controlling whether the key can be used for deriving. Thus, if CKR_KEY_FUNCTION_NOT_PERMITTED is the right return code for the case when CKA_ENCRYPT is not set, it seems reasonable that it would also be the right return code for the case when CKA_DERIVE is not set.
Reference implementations
I looked at some PKCS#11 libraries to check how they handle the case that C_DeriveKey is called on a key with CKA_DERIVE set to CK_FALSE. Most of the implementations I found do not implement the C_DeriveKey function at all (i.e. they always return CKR_FUNCTION_NOT_SUPPORTED). For the libraries that do implement this function, I observed the following behaviors:
OpenSC returns CKR_KEY_TYPE_INCONSISTENT (reference):
CK_ATTRIBUTE derive_attribute = { CKA_DERIVE, &can_derive, sizeof(can_derive) };
...
rv = object->ops->get_attribute(session, object, &derive_attribute);
if (rv != CKR_OK || !can_derive) {
rv = CKR_KEY_TYPE_INCONSISTENT;
goto out;
}
I also checked how OpenSC handles the other attributes that are similar to CKA_DERIVE. It seems the C_EncryptInit function is not implemented in OpenSC (presumably because this is a public key operation?), but C_DecryptInit is. This function implements a check for CKA_DECRYPT (reference), but returns CKR_KEY_TYPE_INCONSISTENT, which goes against the example that was given in the specification of CKR_KEY_FUNCTION_NOT_PERMITTED.
SoftHSMv2 returns CKR_KEY_FUNCTION_NOT_PERMITTED (reference):
// Check if key can be used for derive
if (!key->getBooleanValue(CKA_DERIVE, false))
return CKR_KEY_FUNCTION_NOT_PERMITTED;
openCryptoki: I could not find any check for CKA_DERIVE. They do check CKF_DERIVE against the feature flags of the mechanism and return CKR_MECHANISM_INVALID if the flag is not set (reference), i.e. if the mechanism does not support derivation, but this is not the same as checking CKA_DERIVE against the flags of the key.
illumos-gate (IllumOS being a fork of the discontinued OpenSolaris) also returns CKR_KEY_FUNCTION_NOT_PERMITTED in their soft-key implementation (reference):
/* Check to see if key object allows for derivation. */
if (!(basekey_p->bool_attr_mask & DERIVE_BOOL_ON)) {
rv = CKR_KEY_FUNCTION_NOT_PERMITTED;
goto clean_exit1;
}
Interestingly, in older version of their code they returned CKR_KEY_TYPE_INCONSISTENT instead, and then changed it to CKR_KEY_FUNCTION_NOT_PERMITTED in this commit. The relevant part of the commit message seems to be 6177650 Wrong error code returned when key does not allow requested operation. The ID refers to a ticket in the OpenSolaris bug tracker, which is no longer online. There is an archive of the bug tracker here, but it does not contain any information on this ticket, unfortunately.
Of these reference implementations, I would consider OpenSC to be the most authoritative, in terms of how widely they are used.
Conclusion
Based on the above considerations, I would consider CKR_KEY_FUNCTION_NOT_PERMITTED to be the appropriate return code for the scenario we are discussing. This is supported by the following arguments:
The specification explicitly acknowledges that the list of possible return code for each function might be incomplete. Therefore, CKR_KEY_FUNCTION_NOT_PERMITTED not being listed for C_DeriveKey is not a strong counter-argument.
The specification explicitly lists CKA_ENCRYPT as an example for when CKR_KEY_FUNCTION_NOT_PERMITTED is an appropriate return code. The attribute CKA_ENCRYPT is similar to CKA_DERIVE, so it seems plausible that the return code is also appropriate for CKA_DERIVE.
The specification of CKR_KEY_TYPE_INCONSISTENT suggest that it is about the relation between the mechanism and the key type, not about other key attributes.
OpenSC uses CKR_KEY_TYPE_INCONSISTENT for the scenario we are discussing, but also uses this return code for C_DecryptInit in the case that CKA_DECRYPT is not set, which goes against the example given in the specification of CKR_KEY_FUNCTION_NOT_PERMITTED.
OpenSolaris/IllumOS deliberately switched from CKR_KEY_TYPE_INCONSISTENT to CKR_KEY_FUNCTION_NOT_PERMITTED as the return code for the scenario we are discussing. This suggests they also considered the latter the more fitting return code.

MATLAB doesn't show help for user-created class private methods and properties

This is the problem:
Create a class and set the access to be private for some of the properties or methods.
Use the doc command for the created class. This will auto-generate documentation from your comments and show it in the built-in help browser.
doc classname
The problem is that documentation for the private properties and methods is not shown in the help browser. Is there any way to overcome this problem?
So I spent like 10 minutes using the debugger, jumping from one function to the next, tracing the execution path of a simple doc MyClass call.
Eventually it lead me to the following file:
fullfile(toolboxdir('matlab'),'helptools','+helpUtils','isAccessible.m')
This function is called during the process of generating documentation for a class to determine if the class elements (including methods, properties, and events) are publicly accessible and non-hidden. This information is used later on to "cull" the elements.
So if you are willing to modify MATLAB's internal functions, and you want the docs to always show all methods and properties regardless of their scope, just rewrite the function to say:
function b = isAccessible(classElement, elementKeyword)
b = true;
return
% ... some more code we'll never reach!
end
Of course, don't forget to make a backup of the file in case you changed your mind later :)
(on recent Windows, you'll need to perform this step with administrative privileges)
As a test, take the sample class defined in this page and run doc someClass. The result:
This behaviour is by design - the auto-generated documentation is intended for users of the class, who would only be able to access the public properties and methods.
There's no way that I'm aware of to change this behaviour.
You could try:
Use an alternative system of auto-generating documentation such as this from the MATLAB Central File Exchange (which I believe will document all properties, not just public).
Implement your own doc command. Your doc command should accept exactly the same inputs as the built-in doc command, detect if its inputs correspond to your class/methods/properties etc, and if so display their documentation, otherwise pass its inputs straight through to the built-in doc. Make sure your command is ahead of the built-in on the path.

What is to prefer in Restlet: handleGet, handlePost OR represent, acceptRepresetation?

IMHO, there are two techiques to handle a query for a resource:
For http GET you can override represent(Variant variant) or handleGet().
For http POST the same applies with acceptRepresentation(Representation entity) and handlePost().
The doc for handleGet says:
Handles a GET call by automatically returning the best representation available. The content negotiation is automatically supported based on the client's preferences available in the request. This feature can be turned off using the "negotiateContent" property.
and for represent:
Returns a full representation for a given variant previously returned via the getVariants() method. The default implementation directly returns the variant in case the variants are already full representations. In all other cases, you will need to override this method in order to provide your own implementation.
What are the main differences between these two types of implementations? In which case should I prefer one over the other? Is it right that I can achieve with e.g. handleGet() everything that would work with represent()?
I first started using handleGet setting the entity for the response. When I implemented another project I used represent. Looking back i can't really say one way is better or clearer than the other. What are your expirences for that?
I recommend using represent(Variant) because then you’ll be leveraging the content negotiation functionality provided by the default implementation of handleGet(Request, Response).
BTW, lately I've started using the annotation-based syntax instead of overriding superclass methods, and I like it. I find it clearer, simpler, and more flexible.
For example:
#Post('html')
Representation doSearch(Form form) throws ResourceException {
// get a field from the form
String query = form.getFirstValue("query");
// validate the form - primitive example of course
if (query == null || query.trim().length() == 0)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Query is required.");
// do something
SearchResults searchResults = SearchEngine.doSearch(query);
// return a HTML representation
return new StringRepresentation(searchResults.asHtmlString(), MediaType.TEXT_HTML);
}
The advantages of using this approach include the incoming representation being automatically converted to a useful form, the method can be named whatever makes sense for your application, and just by scanning the class you can see which class methods handle which HTTP methods, for what kind of representations.