Giter VIP home page Giter VIP logo

auto-increment's Introduction

Typegoose

(These badges are from typegoose:master)
Node.js Tests codecov.io npm

Define Mongoose models using TypeScript classes

Migration

Migration Guides:
(Date format: dd-mm-yyyy)

Basic usage

import { prop, getModelForClass } from '@typegoose/typegoose';
import * as mongoose from 'mongoose';

class User {
  @prop()
  public name?: string;

  @prop({ type: () => [String] })
  public jobs?: string[];
}

const UserModel = getModelForClass(User); // UserModel is a regular Mongoose Model with correct types

(async () => {
  await mongoose.connect('mongodb://localhost:27017/', { dbName: 'test' });

  const { _id: id } = await UserModel.create({ name: 'JohnDoe', jobs: ['Cleaner'] });
  const user = await UserModel.findById(id).exec();

  console.log(user); // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }
})();

Motivation

A common problem when using Mongoose with TypeScript is that you have to define both the Mongoose model and the TypeScript interface. If the model changes, you also have to keep the TypeScript interface file in sync or the TypeScript interface would not represent the real data structure of the model.

Typegoose aims to solve this problem by defining only a TypeScript interface (class), which needs to be enhanced with special Typegoose decorators (like @prop).

Under the hood it uses the Reflect & reflect-metadata API to retrieve the types of the properties, so redundancy can be significantly reduced.

Instead of writing this:

// This is a representation of how typegoose's compile output would look like
interface Car {
  model?: string;
}

interface Job {
  title?: string;
  position?: string;
}

interface User {
  name?: string;
  age!: number;
  preferences?: string[];
  mainJob?: Job;
  jobs?: Job[];
  mainCar?: Car | string;
  cars?: (Car | string)[];
}

const JobSchema = new mongoose.Schema({
  title: String;
  position: String;
});

const CarModel = mongoose.model('Car', {
  model: string,
});

const UserModel = mongoose.model('User', {
  name: { type: String },
  age: { type: Number, required: true },
  preferences: [{ type: String }],
  mainJob: { type: JobSchema },
  jobs: [{ type: JobSchema }],
  mainCar: { type: Schema.Types.ObjectId, ref: 'Car' },
  cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }],
});

You can just write this:

class Job {
  @prop()
  public title?: string;

  @prop()
  public position?: string;
}

class Car {
  @prop()
  public model?: string;
}

class User {
  @prop()
  public name?: string;

  @prop({ required: true })
  public age!: number; // This is a single Primitive

  @prop({ type: () => [String] })
  public preferences?: string[]; // This is a Primitive Array

  @prop()
  public mainJob?: Job; // This is a single SubDocument

  @prop({ type: () => Job })
  public jobs?: Job[]; // This is a SubDocument Array

  @prop({ ref: () => Car })
  public mainCar?: Ref<Car>; // This is a single Reference

  @prop({ ref: () => Car })
  public cars?: Ref<Car>[]; // This is a Reference Array
}

Extra Examples


Requirements & Install

Typegoose's Quick Start Guide

Testing

yarn install
yarn run test

Versioning

This Project should comply with Semver. It uses the Major.Minor.Fix standard (or in NPM terms, Major.Minor.Patch).

Join Our Discord Server

To ask questions or just talk with us, join our Discord Server.

Documentation

Known Issues

Here are the known-issues

FAQ

Here is the FAQ

Notes

  • Please don't add +1 or similar comments to issues. Use the reactions instead.

auto-increment's People

Contributors

hasezoey avatar jonbarrow avatar nasr18 avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

auto-increment's Issues

Create ID auto_increase inside array for each object

I have structure schema below

export class Question extends BaseEntity {
  @Prop({ type: Number, unique: true })
  _id: number;
  @Prop({
    type: [
      {
        id_meta: {
          type: Number,
          unique: true,
        },
        question: [String],
        image_sup: {
          type: String,
          required: false,
          default: null,
        },
        answer_correct: {
          answer: [String],
          image_sup: {
            type: String,
            required: false,
            default: null,
          },
        },
        answer_system: {
          answer: [String],
          image_sup: {
            type: String,
            required: false,
            default: null,
          },
        },
      },
    ],
    default: [],
  })
  question_meta: [
    {
      id_meta: number;
      question: [string];
      image_sup?: string;
      answer_correct: {
        answer: string[];
        image_sup: string;
      };
      answer_system: {
        answer: string[];
        image_sup: string;
      };
    },
  ];
}
QuestionSchema.plugin(AutoIncrementID, {
  field: '_id',
  startAt: 1,
} as AutoIncrementIDOptions);

And I expect id_meta auto_increase

Can auto increment id with `insertMany`?

This is my model, but auto increment only worked on create, but not working on insertMany.

Such as this.

await this.noteModel.insertMany(models)

Only worked this.

for await (const mo of models) {
      await this.noteModel.create(mo)
    }
@plugin<AutoIncrementIDOptions>(AutoIncrementID, {
  field: 'nid',
  startAt: 1,
})
@plugin(uniqueValidator)
@index({ created: -1 })
@index({ text: 'text' })
@index({ modified: -1 })
@index({ created: -1, modified: -1 })
@index({ nid: -1 })
export default class Note extends BaseCommentIndexModel {
  @prop({ required: false, unique: true })
  public nid: number
}

Can you fix it? thank you.

Not working with upsert?

I have a model User:

@plugin(AutoIncrementID, { field: 'uid' })
class User {
  @prop()
  uid: number
  ...
}

here is the code that find or create a user:

  const user = await User.findOneAndUpdate(
    { _id: userId },
    {
      $setOnInsert: {
        nickname,
      },
    },
    { upsert: true, new: true, setDefaultsOnInsert: true },
  ).exec()

and uid is not automatically added to the document.

After enabling debug log I can confirm that schema.pre('save', ... is not triggered.

And here is the document in identitycounters:

{
    "_id" : ObjectId("5efadb0a23647200182d4c3d"),
    "count" : -1,
    "model" : "users",
    "field" : "uid",
    "__v" : 0
}

Support mongoose v6.1.x

What is the Problem?

Should support mongoose v6.1.x,
current peer dependency is mongoose@~6.0.7

Convert _id from ObjectId to incremental number

I read the docs and I wrote this code :

import { prop, plugin } from "@typegoose/typegoose";
import { AutoIncrementIDOptions, AutoIncrementID } from "@typegoose/auto-increment";

@plugin<AutoIncrementIDOptions>(AutoIncrementID, {})
export class BaseModel<T> {

    @prop()
    _id: number;

    @prop()
    name: string;

}

but it doesn't work the _id field is still an objectId not a auto incremented number.
Can you please tell me how can I implement this ?

Unmet peer dependency error with mongoose 7.6.x

I'm using @typegoose/auto-increment 3.6.0 with mongoose 7.6.3. Version 3.6.0 is supposed to support mongoose 7.6.x, but I'm still getting unmet peer mongoose@~7.5.0: found 7.6.3.

Looking at package.json, I see "mongoose": "~7.6.1" under devDependencies, but there's still "mongoose": "~7.5.0" under peerDependencies, which looks like the root cause for this issue.

Could you please look into it? Thank you.

Increment key based on another field

Let's say we have Incremented Value(ref) in the document which need to be incremented based on another field(shopId)

{
   "ref": 12,
   "shopId":1
},
{
   "ref": 13,
   "shopId":1
},
{
   "ref": 1,
   "shopId":2
},
{
   "ref": 2,
   "shopId":2
},
{
   "ref": 14,
   "shopId":1
}

What kind of approach can we have? ( the two properties are compound index)

Mongoose 7+ compatibility

Describe what you need

Hello, I'd like to use this package as a replacement for mongoose-sequence, which breaks with the newest Mongoose version 7.
This package's peerDependency conflicts with Mongoose 7 though, as it is only โ€œ~6.10.0โ€ which isn't compatible with the new Mongoose version.

Considering Mongoose 7 dropped callback support in many places, this may not be feasible, but I'd be happy to hear from you regarding this issue.

Do you have already an idea for the implementation?

no

mongoose 6.8 compatibility

Hello,

npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/mongoose
npm ERR!   mongoose@"^6.8.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer mongoose@"~6.6.0" from @typegoose/[email protected]
npm ERR! node_modules/@typegoose/auto-increment
npm ERR!   @typegoose/auto-increment@"*" from the root project```

Consider supporting `overwriteModelName` to be a function

Describe what you need | want

ability to have overwriteModelName be a function, with the arguments being the current model so it can be decided "on-the-fly" and the plugin could be applied to a base-model and have specific cases for some models but not all

Do you have already an idea for the implementation?

change to support overwriteModelName to be a function, and call it every-time the name is required

Auto Increment doesn't Increment field value | TypeScript

I'm using

  • auto-increment: last version
  • mongoose: 5.x
  • TypeScript 4.1.2

My model

import mongoose, { Schema, Document } from "mongoose";
import { AutoIncrementSimple } from "@typegoose/auto-increment";

export interface ICountry extends Document {
    name: string;
    code: string;
    counter: number,
}

const CountrySchema: Schema = new Schema(
    {
        name: {
            type: String,
            required: [true, "The country name is required"],
            unique: true,
        },
        code: {
            type: String,
            required: [true, "The country code is required"],
            unique: true,
        },
        counter: {
            type: Number,
            default: 1,
            //unique: true,
        },
    },
    {
        timestamps: false,
    }
);
CountrySchema.plugin( AutoIncrementSimple, [{ field: 'counter', incrementBy: 1 }] );

const CountryModel = mongoose.model<ICountry>( "Country", CountrySchema );
export default CountryModel;

And my controller

const data = {
  name: req.body.name_uz,
  code: req.body.code,
};
const countryAdd = new CountryModel(data);
await countryAdd
  .save()
  .then(async (obj: ICountry) => {
    // Return response
    res.status(200).json({
      status: "Success",
      data: obj,
    });
  })
  .catch((reason) => {
    //...
  });

If I start, it only saves the default value. Am I doing something wrong? Or is it not working?
I also tried the pre function, but it didn't work either. How to make the value on the counter automatically growing?
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.