-
Notifications
You must be signed in to change notification settings - Fork 483
Description
Hello, first of all thank you to the devs and contributors for this great project.
Reading the docs for Collection.prototype.insert it says:
Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc.
It is not clear to me whether we're allowed to insert objects that are constructed like new Foo() instead of just plain kv objects like {a: 1, b: 2} and if the former could lead to unspecified behavior that might change arbitrarily in the future.
I tested this, with this code:
user@debian:~$ cat _caca.js
const loki = require("lokijs");
// class
function Foo(a, b) { this.a = a; this.b = b; }
Foo.prototype.hello = function() { console.log("hello", this.a, this.b); }
const db = new loki();
db.addCollection("objsWithFoo");
const foo = new Foo(42, 69);
const rv1 = db.getCollection("objsWithFoo").insert({ foo });
console.log(rv1);
rv1.foo.hello();
const rv2 = db.getCollection("objsWithFoo").get(rv1['$loki']);
console.log(rv2);
rv1.foo.hello();
console.log();
console.log(rv1.foo === foo);
console.log();
console.log(db.serialize());
user@debian:~$ node _caca.js
{
foo: Foo { a: 42, b: 69 },
meta: { revision: 0, created: 1758648922743, version: 0 },
'$loki': 1
}
hello 42 69
{
foo: Foo { a: 42, b: 69 },
meta: { revision: 0, created: 1758648922743, version: 0 },
'$loki': 1
}
hello 42 69
true
{"filename":"loki.db","collections":[....snipped
The prettified json string resulting from db.serialize looks like:
{
"filename": "loki.db",
"collections": [
{
"name": "objsWithFoo",
"data": [
{
"foo": {
"a": 42,
"b": 69
},
"meta": {
"revision": 0,
"created": 1758646847482,
"version": 0
},
"$loki": 1
}
],
"idIndex": [
1
],
"binaryIndices": {},
"constraints": null,
... ... ...
As you can see, serializing to JSON naturally gives a "plain object" and if we were to deserialize it into a fresh db and get a document it wouldn't bee an instance of Foo anymore, this is expected.
However, during the lifetime of the program, when we use the existing db, it does retrieve the exact same object. Can I rely on this behavior?
Thanks.
Regards,
~ Mihai