antsa-mongoose-fixture

1.0.5 • Public • Published

MONGOOSE FIXTURES

This is a simple data fixtures for mongoose

Installation

$ npm install antsa-mongoose-fixture

Feautures

  • Drop database on each fixtures loading
  • ObjectId _id autogeneration on data fixture
  • Fixtures loading

Usage

Define your model first

// Define your model
const User = mongoose.model(
  "User",
  new Schema({
    username: String,
  })
);

const Post = mongoose.model(
  "Post",
  new Schema({
    title: String,
    author: { type: Schema.Types.ObjectId, ref: "User" },
  })
);

Define data for fixtures and use fixtures.addId() to generate _id

const { fixtures } = require("antsa-mongoose-fixtures");

const users = [
  {
    username: "Antsa",
  },
  {
    username: "Fiderana",
  },
  {
    username: "Miando",
  },
];

fixtures.addId(users); // Generate _id to simplify reference usage

const posts = [
  {
    title: "Post 1",
    author: users[0]._id, // Some reference on user 0
  },
  {
    title: "Post 2",
    author: users[2]._id, // Some reference on user 2
  },
];

fixtures.addId(posts);

Load fixtures now with fixtures.load() after mongoose connection is initialized

const { default: mongoose } = require("mongoose");

mongoose.connect(process.env.MONGO_URL); // Your mongoose connection

const { fixtures } = require("antsa-mongoose-fixtures");
fixtures.load([users, User], [posts, "Post"]); // You can use model directly or model name

Usage in testing

Autogenerated _id is very usefull in automated test

// Without fixtures
it("should get user by id", async () => {
  const actual = await User.findById(
    ObjectId("5ferfsdkhffkjadfkjashdffdaj")
  ).exec();
  expect("Antsa").equal(actual.username);
});

// With fixtures autogenerated _id
it("should get user by id", async () => {
  fixtures.addId(users);
  const actual = await User.findById(users[0]._id).exec();
  expect("Antsa").equal(actual.username);
});

Readme

Keywords

Package Sidebar

Install

npm i antsa-mongoose-fixture

Weekly Downloads

2

Version

1.0.5

License

MIT

Unpacked Size

8.66 kB

Total Files

14

Last publish

Collaborators

  • antsa1615