Cara menggunakan create schema in mongodb

A database model is a type of data model that determines the logical structure of a database and fundamentally determines in which manner data can be stored, organized and manipulated. There are many kinds of data models, but the most popular type is the relational model, which uses a table-based format.

Usually, the data warehousing staff of a business will design one or more types of data models in order to most effectively normalize the tables and pan how to most efficiently store and retrieve business data. Another advantage of doing this exercise upfront is that many professional tools like Navicat can utilize the models as plans and build the database according to their specifications.

That being said, it is an unfortunate fact that all-too-often, data models get misplaced or deleted over time. In that event, DBAs have no recourse but to either redraft the models from scratch or, if they're in the know, let their Database Management Tool create models for them based on the existing database.

In today's tip, we'll learn how to create a model from a variety of database objects in Navicat Premium.

The process of extracting design information from a software product is known as “reverse engineering”. In Navicat, you can reverse engineer a database/schema, tables or views to a physical model.

To reverse engineer a database schema, right-click it in the Navigation Pane and choose Reverse Schema to Model… from the popup menu:

Cara menggunakan create schema in mongodb

Navicat will then generate a physical model from the selected schema and open it in a new Model window:

Cara menggunakan create schema in mongodb

You can then work with the new model just as you would one that you created from scratch. For example, you can add relationships, move objects around, and save the model.

Individual tables or views may be reverse engineered into physical models as well by right-clicking them in the Navigation Pane and selecting Reverse Tables to Model… from the popup list:

Cara menggunakan create schema in mongodb

That will open the selected table in a new Model window:

Cara menggunakan create schema in mongodb

It is also possible to select more than one table or view by selecting them in the Objects pane:

Cara menggunakan create schema in mongodb

Right-clicking anywhere within the selection and choosing Reverse Tables to Model… from the popup list will now open those tables/views in a new Model window:

Cara menggunakan create schema in mongodb

Navicat also supports the importing of databases, schema, tables or views from the Model window. A step-by-step wizard is provided to guide you through the import process.

  • Begin by opening a new Model window, either by:
    • Clicking the Model button on the main toolbar followed by the New Model button on the Objects toolbar:
    • Cara menggunakan create schema in mongodb

      OR

    • Selecting File > New > Model… from the main menu:
    • Cara menggunakan create schema in mongodb
  • Enter the Database Vendor and Version number in the New Model dialog and click OK to open a new Model window for that product:
  • Cara menggunakan create schema in mongodb
  • Select File -> Import from Database from the Model window menu:
  • Cara menggunakan create schema in mongodb
  • On the Import from Database dialog, select a Connection.
  • Choose the databases, schemas, tables or views you want to import:
  • Cara menggunakan create schema in mongodb
  • Click Start to create the model from the selected objects.

Should the need ever arise to reverse engineer database objects into a model, Navicat has you covered. Available in Navicat Premium and Enterprise Editions, the Reverse Engineering feature takes the challenge out of physical model creation from databases, schema, tables or views.

Untuk mengkases data, mongoose membutuhkan model. Model dapat dianalogian seperti blueprint untuk membuat document. Jadi seperti class pada javascript.

Operasi Create, Read, Update dan Delete dilakukan melalui model. Untuk membuat model kita memerlukan schema.

Schema digunakan untuk mendeskripsikan data, default value, data validasi dan lainnya. Schema menggunakan data type Javascript.

Berikut contoh paling sederhana sebuah schema.

const tourSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    price: Number
});

Dari contoh diatas, bisa kita kembangkan lebih detail dengan mendefinisikan schema type option.

const tourSchema = new mongoose.Schema({
    name: {
        type: string,
        required: [true, 'Nama tour harus diisi'],
        uniqure: true
    },
    rating: {
        type: Number,
        default: 4.5
    }
    price: {
        type: Number
,
        required: [true, 'Price harus diisi']
    }
});

{type: string, required: [true, ‘Nama tour harus diisi’], unique: true} disebut schema type option. Setiap type field bisa berbeda. Pada contoh: field name

  • Type data adalah string.
  • required true berarti harus diisi, bila terjadi error, message yang ditampilkan adalah ‘Nama harus diisi’.
  • uniqure : true berarti, tidak bisa insert data dengan nama tour yang sama.

Setelah schema didefinisikan, berikutnya adalah membuat model berdasarkan schema tersebut.

const Tour = mongoose.model('Tour', tourSchema);

Setelah model selesai dibuat, berikutnya kita gunakan untuk membuat document dan menyimpannya ke database server.

const newTour = Tour({
    name: 'Test Tour 1',
    rating: 4,
    price: 450
});

newTour.save().then(doc =>{
    console.log(doc);
}).catch(err =>{
    console.log('ERROR', err);
});

Jika Anda buka website Atlas (MongoDB Cloud), buka bagian collections, maka data sudah tersimpan di cloud.

Cara menggunakan create schema in mongodb

Berikut isi lengkap file server.js

const mongoose = require('mongoose');
const app = require('./app');

const db = 'mongodb+srv://:@cluster0.x6e8z.mongodb.net/?retryWrites=true&w=majority';

mongoose.connect(db, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
}).then(con => {
    console.log('DB Connected');
});


const tourSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Nama tour harus diisi'],
        unique: true
    },
    rating: {
        type: Number,
        default: 4.5
    },
    price: {
        type: Number,
        required: [true, 'Harga tour harus diisi']
    }
});

const Tour = mongoose.model('Tour', tourSchema);

const newTour = Tour({
    name: 'Test Tour 3',
    rating: 4,
    price: 450
});

newTour.save().then(doc =>{
    console.log(doc);
}).catch(err =>{
    console.log('ERROR', err);
});

const port = 3000;
app.listen(port, ()=>{
    console.log(`Listening on port ${port}...`);
});

Code schema dan model akan dibuat difile terpisah. Contoh program diatas adalah hanya sebagai testing proses pembuatan schema, model dan proses insert data ke mongoDB.