0

Lokijs giving incorrect find response in Node JS environment

This is an example taken from online:

// This database has already been created for you.
// var db = new loki('sandbox');

// Add a collection to the database
var items = db.addCollection('items');

// Add some documents to the collection
items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' });
items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' });
items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' });
items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' });

// Find and update an existing document
var tyrfing = items.findOne({'name': 'tyrfing'});
tyrfing.owner = 'upated';


// These statements send to Text Output
logText('tyrfing value :');
logObject(tyrfing);
logText('tyrfing items');
logObject(items.find({ 'name': 'tyrfing' }));

// This statement sends to Inspector
inspectObject(db);

After inserting couple of dummy data; I am fetching from the same collection and assign that to a templ variable called "tyrfing";

Now, here is the issue; I made a update to the owner property with the new value called "upated". eventhough I didn't made loki save/update to the update;

When I called find on name as "tyrfing" it is giving the response as

odins items
[
  {
    "name": "tyrfing",
    "owner": "upated",
    "maker": "dwarves",
    "meta": {
      "revision": 0,
      "created": 1554823595464,
      "version": 0
    },
    "$loki": 3
  }
]

Which is incorrect, I am expecting the owner name as "Svafrlami" in the response; as I didn't made any db commit;

Please correct me, if I made anything wrong here;

You can test this code in online here by copy pasting this : http://www.obeliskos.com/LokiSandbox/

Ram Kowsu
  • 711
  • 2
  • 10
  • 30

2 Answers2

1

@Creator actually the LokiJS way of doing this is to pass the clone option in the collection constructor: docs You can also specify which method of cloning you want to use.

Joe Minichino
  • 2,793
  • 20
  • 20
0

I figured it out, after spending few mins; items.find is returning the actual/real object reference; so if I make any changes it wil reflect in the original as well;

So that I cloned the original object what I got from the find and then made the changes to cloned object and it worked :)

Here is the code :

var clone = require('clone');
// Find and update an existing document
var tyrfing = items.findOne({'name': 'tyrfing'});
var temptyrfing = clone(tyrfing);
temptyrfing.owner = 'upated';


// These statements send to Text Output
logText('tyrfing value :');
logObject(temptyrfing);
logText('tyrfing items');
logObject(items.find({ 'name': 'tyrfing' }));

I used "clone" npm module to clone the object

Please post me, if any other possiblities as well;

Ram Kowsu
  • 711
  • 2
  • 10
  • 30