Search code examples
node.jstypescriptmongodbmongoosemongoose-schema

How to insert data in mongodb using mongoose in typescript?


I had implemented a typescript code for a crud API but currently, I'm facing an issue while inserting data using API using the mongoose package. AS my database is MongoDB so I have used this package.

import Transaction from 'mongoose-transactions-typescript';

I am working on typescript project so that's why I have used this package

public async createAffiliateUser(res_data: any){
        console.log("Function");
        

const transaction = new Transaction();

        console.log("Function123");
        const AffiliateUserModelName = 'affiliateusers'; // COLLECTION name
        console.log(res_data);
        await transaction.insert(AffiliateUserModelName, {
            name: res_data.name,
            userName: res_data.userName,
            groupId: res_data.groupId,
            commissionCount: res_data.commissionCount,
            commissionAmount: res_data.commissionAmount,
            is_active: res_data.is_active
        });
        
        return await transaction.run();
    }

In the above code highlighted line throwing an error like this

TypeError:mongoose_transactions_typescript_1.default is not a constructor

In the above function when I tried to use default create method of mongoose it inserting only single column data even though passing full data as below

{
    "name": "Test",
    "userName":"test123",
    "groupId": "1",
    "commissionCount": 1,
    "commissionAmount": 2,
    "is_active": true
}

So if anyone knows how to insert data in MongoDB using typescript or a solution for the above problem then pls help me to resolve this?

Thank you


Solution

  • I don't know why are you using this code structure in order to use mongoose.

    The steps that I follow in order to use correctly mongodb documents with mongoose are these:

    1. create a mongoose model schema like this:
    // I usually like create this file in a database folder
    import mongoose, { Document, Model } from "mongoose";
    const Schema = mongoose.Schema;
    
    // creating the actual mongoose schema
    
    const UserSchema = new Schema(
      {
        firstName: {
          type: String,
        },
        lastName: {
          type: String,
        },
        username: {
          type: String,
        },
        lang: {
          type: String,
          default: "it",
        },
      },
      { timestamps: true }
    );
    
    // exporting the type in order to have all the correct linting
    
    export interface IUser extends Document {
      id: string;
      firstName: string;
      lastName?: string;
      username?: string;
      createdAt: Date | number;
      updatedAt: Date | number;
    }
    
    // registering in mongoose models the schema with the relative interface
    
    const User =
      (mongoose.models.User as Model<IUser>) ||
      mongoose.model<IUser>("User", UserSchema);
    export default User;
    
    

    at this point let's suppose that you have a tree similar to this:

    root_folder
              |-- database
              |        |-- User.ts
              |
              |-- controllers
                          |-- addUser.ts
    
    
    1. creating the document in the collection:
    import { User } from "../../database/User.ts"
    
    async function addUser(){
      const newUser = await new User({firstName: "foo", lastName: "bar", username:"testUser"}).save()
    }
    

    and now you should have your fresh document in the users collection