Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ray0324 opened this issue Nov 29, 2021 · 2 comments
Open

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

ray0324 opened this issue Nov 29, 2021 · 2 comments

Comments

@ray0324
Copy link

ray0324 commented Nov 29, 2021

//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" }
    ]
  }
}
@stevenjoezhang
Copy link
Member

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

@stevenjoezhang
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants