简体   繁体   English

使用猫鼬和打字稿创建模式

[英]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.试图创建新的猫鼬模式,但问题是我总是得到只有两列的新集合:_id 和 __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.我的错,代码没问题,但问题在于通过 google chrome 中的邮递员扩展将值发布到服务器。 Just had to add Content-Type = application/json.只需添加 Content-Type = application/json。 That's it.就是这样。 Guess I can close this question now.猜猜我现在可以关闭这个问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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