lokijs storing in filesystem not in in-memeory

641 Views Asked by At

I tried the following basic example from the online;

var loki = require('lokijs');
var lokiDatabase = new loki('oops.json');

var collection = lokiDatabase.addCollection('props',{
    indices: ['name']
});


function hello() {
    var insertjson = {name:'Ram'};
    collection.insert(insertjson);
    lokiDatabase.saveDatabase();
    var select = collection.findOne({name:'Ram'});
    console.log('select response:'+ select.name);
 }

hello();

I am able to get the output with findOne method;

But here, the question is; as tutorials said, LokiJS is an in-memory database; wheras, I can see all the inserts & updates are presenting in the oops.json file.

Where we are storing/from to in-memory here?

Did I understood the concepts wrong?

2

There are 2 best solutions below

1
On

enter image description here

//lokirouter.js
const db=require('./lokidb')
const router=require('express').Router
class Erouter{
static get(){
router.get("/",(req,res)=>{
db.loadDatabase({},function(){
    try{
    const data=db.getCollection('items').find({})
    res.send(data).status(200)
    }
    catch(r){
        res.status(500).send(`${r}`)
    }
})
})
router.post("/",(req,res)=>{
db.loadDatabase({},()=>{
    try{
    const data=db.getCollection('items').insert(req.body.criteria)
    db.saveDatabase(data)
    db.save(data)
    res.send(data).status(200)
    }
    catch(r){
    res.status(500).send(`${r}`)
    }
    })
    })
return router
}}
module.exports=Erouter

//lokidb.js
var loki=require('lokijs')
var db = new loki('loki.db');
var items = db.addCollection('items');
module.exports=db

//lokiapp.js
const lokirouter=require('./lokirouter')
const express =require("express")
const bodyParser = require('body-parser')
const app=express()
const db=require('./lokidb')
const port=8000;
app.listen(port)
console.log("Server Started"+ " "+port)
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use("/",lokirouter.get())
1
On

Lokijs is a document driven database,besides not necessary to store records only a json file,can also store in local database file creating local_database.db for instance. As previous mentioned answer below you have to run it using postman. when you insert records in request body in json format ex:{ "criteria":{"name":"jason"} } it will get inserted into the local_database.db file.Similarly to retrive the records you can call get api. Since to find a particular record you can use findOne({name:"jason"}).