I can’t create a Schema in Mongoose

Asked

Viewed 150 times

0

Hello!

I am learning to use Mongoose. I am trying to create a model, but the terminal is returning the following error: "Cannot read Property 'Schema' of Undefined"

Where I’m going wrong?

Follow the codes:

User ts.

import mongoose from 'mongoose';

let Schema = mongoose.Schema;

const  UserSchema = new Schema({
name: {
    type: String,
    default: '',
    trim: true
},
email: {
    type: String,
    default: '',
    trim: true
},
password: {
    type: String,
    default: ''
},
register: {
    type: Date
}
});

export const User = mongoose.model('user', UserSchema);

index ts.

import * as express from 'express';
import { connect } from './app/database/db';
import { User }  from './app/models/User';

const server = express();

if (connect) {
console.log('Conentado à base de dados com suceso.');

server.listen(3000, () => {
    console.log('Servidor rodando em http://localhost:3000');
    } 
);
} else {
    console.log('Erro ao tentar conectar à base de dados.');
}

server.get('/user', (req, res) => {
    User.find()
.then((users) => {
    res.json({
        confirmation: "Success!",
        data: users
    })
})
.catch((err) => {
    res.json({
        confirmation: "Fail.",
        message: err.message
    })
})
})

inserir a descrição da imagem aqui

  • Mongoose may not have the statement export default, then try to care for it import * as mongoose from 'mongoose'.

2 answers

0

Check the first and last line of your script: In the forefront: import mongoose from 'mongoose'; Change to :const mongoose - require('mongoose')

On the last line: export const User = mongoose.model('user', UserSchema); Change to: module.exports = mongoose.model('User', UserSchema)

With these changes you can move on with Mongoose.

0

So you must solve your problem

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const UserSchema = new Schema({
    name: {
        type: String,
        default: '',
        trim: true
    },
    email: {
        type: String,
        default: '',
        trim: true
    },
    password: {
        type: String,
        default: ''
    },
    register: {
        type: Date
    }
})

module.exports = mongoose.model('User', UserSchema)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.