PersistenceExtensions and mongodb

  • Platform information:
    • docker image: openhab/openhab:3.2.0.RC1
    • openHAB version: 3.2.0
  • Issue of the topic: Error when trying to use PersistenceExtensions with MongoDB persistence service.
  • Please post configurations (if applicable):

I’m writing a script in EcmaScript 2021 (JSScripting addon)

openhab = require('@runtime');
logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + this.ruleUID);
openhab.PersistenceExtensions = Java.type('org.openhab.core.persistence.extensions.PersistenceExtensions');
var last = openhab.PersistenceExtensions.lastUpdate(openhab.itemRegistry.getItem('Thermometer'));;

When I change persistence service to RRD4j - everything works as expected, but when I change it to ‘mongodb’, I’m always getting this error (the same error appears for all other methods, like for example “previousState” and so on).

 Script execution of rule with UID '86c39f1c99' failed: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Number (java.lang.String and java.lang.Number are in module java.base of loader 'bootstrap')

Is there another way, how I could query mongodb from scripts instead of using PersistenceExtensions which it seems doesn’t support MongoDB? Or am I doing something wrong? Thanks.

If you are using JSScripting you are probably better off using the built in Helper Libraries which come with the add-on now. That abstracts a lot of that old JSR223 stuff away from you and makes a much clearner experience now.

NOTE: the following assumes that the “Use Built in Variables” is still enabled (it’s enabled by default).

logger = log(this.ruleUID);
var last = items.getItem("Thermometer").history.lastUpdate();;

The docs for the library have been merged with the binding docs: JavaScript Scripting - Automation | openHAB

Note that the helper library, where ever possible, converts to pure JavaScript Objects instead of giving you a reference to a Java Object like @runtime does. So lastUpdate() in this case returns a JavaScript Date, not a Java ZonedDateTime.

But that doesn’t address your specific problem with MongoDB. Unfortunately there isn’t enough there to really tell me what is going on. You have a String and it doesn’t like it and expected it to be a Number. But there isn’t anything to indicate where that error is coming from (do you have a stack trace and just failed to post it) nor why it happens only with MongoDB. Have you by chance changed the type of this Item?

You can use MongoDB’s REST API and the sendHttpXRequest openHAB actions, but of course you’ll then need to parse out the JSON(?) you get back.

The docs for the MongoDB clearly states that queries are possible.