使用mongoose和typescript创建模式

时间:2017-02-12 21:22:36

标签: node.js typescript mongoose

尝试创建新的mongoose模式,但问题是我总是只使用两列来获取新集合:_id和__v。就是这样,没有我的架构列。 这是架构代码:

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;

用户模型非常简单:

import mongoose = require('mongoose');

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

export default UserModel;

数据访问层:

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;

尝试创建新用户后,它会在数据库中创建新文档,但只有两个默认列...

1 个答案:

答案 0 :(得分:1)

我的错,代码还可以,但问题在于通过google chrome中的postman扩展名向服务器发布值。只需要添加Content-Type = application / json。就是这样。 我猜我现在可以关闭这个问题了。