简体   繁体   中英

Creating schema with mongoose and typescript

Trying to create new mongoose schema but the issue is I am always getting new collection with only two columns: _id and __v. That's it, no my columns from schema. Here is the schema code:

import DataAccess from '../DataAccess';
import IUserModel from '../../model/interfaces/UserModel';

var mongoose = DataAccess.mongooseInstance;
var mongooseConnection = DataAccess.mongooseConnection;
class UserSchema {
  static get schema() {
    var schema = mongoose.Schema({
      email: {
        type: String,
        required: false
      },
      firstName: {
        type: String,
        required: false
      },
      lastName: {
        type: String,
        required: false
      },
      createdAt: {
        type: Date,
        required: false
      }
    });

    return schema;
  }
}

var schema = mongooseConnection.model<IUserModel>('Users', UserSchema.schema);

export default schema;

User model is pretty simple:

import mongoose = require('mongoose');

interface UserModel extends mongoose.Document {
  email: string;
  firstName: string;
  lastName: string;
  createdAt: Date;
}

export default UserModel;

Data access layer:

import mongoose = require('mongoose');

class DataAccess {
  static mongooseInstance: any;
  static mongooseConnection: mongoose.Connection;

  static connect(): mongoose.Connection {
    const MONGODB_CONNECTION: string = 'mongodb://localhost:27017/dbname';

    if (this.mongooseInstance) return this.mongooseInstance;

    this.mongooseConnection = mongoose.connection;
    this.mongooseConnection.once('open', () => {
      console.log('Connected to mongodb');
    })
    this.mongooseInstance = mongoose.connect(MONGODB_CONNECTION);
    return this.mongooseInstance;
  }
}

DataAccess.connect();
export default DataAccess;

Once I am trying to create new user it creates new document in database but with only two default columns ...

My fault, the code is ok, but the issue was in posting values to the server via postman extension in google chrome. Just had to add Content-Type = application/json. That's it. Guess I can close this question now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM