hexojs / warehouse

JSON database

Home Page:https://hexojs.github.io/warehouse/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

pre-save hooks doesn't make sense when use db.load()

ray0324 opened this issue · comments

//db.js
import Database from "warehouse";
import path from "path";
import fs from "fs";


const dbpath = path.resolve("./db.json");

const db = new Database({ path: dbpath });

await db.load();

console.log("db loaded...");

export default db;
//category.js
import Database from "warehouse";
import db from "./db.js";

const { Schema } = Database;

const schema = new Schema({
  name: { type: String, required: true },
});

schema.pre("save", async (data) => {
  const { name, parent } = data;
  if (!name) return;
  const categories = db.model("categories");
  const cat = await categories.findOne({ name });
  if (cat) {
    throw new Error(`Category \`${name}\` has already existed!`);
  }
});

const Category = db.model("categories", schema);

export default Category;
// cli.js
import Category from "./category.js";
import db from "./db.js";

const cat = await Category.save({ name: "Javascript" });

console.log("saved:", cat);

db.save();
//db.json repeat so much!!!
{
  "meta": { "version": 0, "warehouse": "4.0.0" },
  "models": {
    "posts": [],
    "categories": [
      { "name": "Javascript", "_id": "ckwkujczh0000587nh75rhpcl" },
      { "name": "Javascript", "_id": "ckwkuqnr10000io7nb3ocey48" },
      { "name": "Javascript", "_id": "ckwkuqqpm0000u07n4gxg94r1" },
      { "name": "Javascript", "_id": "ckwkus0pb0000887nal5m0mxh" },
      { "name": "Javascript", "_id": "ckwkus2op0000dw7n5twndlvm" },
      { "name": "Javascript", "_id": "ckwkus3ko0000x07n36056e7i" },
      { "name": "Javascript", "_id": "ckwkus48c0000w47n962sfmfo" },
      { "name": "Javascript", "_id": "ckwkusz930000bg7n2rsm792b" }
    ]
  }
}
commented

Confirmed that when running cli.js, the callback function of pre-save hook is actually not executed

commented

The problem is here:

if (this._models[name]) {
return this._models[name];
}

When running db.model("categories", schema), the pre-save hook is actually not registered. The model of Category is loaded directly from db.json, without the information of pre-save hook.