In models/api.js
- First import mongoose
- Then create a Schema function variable
- Create the schema to be created.
- type could be String, Number, and Schema.Types.ObjectId in case it needs to refer document from some other Collection.
- In case you want to set up action methods use Schema.methods like used in below example
- Finally export it
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
imageUrl: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
}, {timestamps: true});
productSchema.methods.deleteAll = function() {
this = { };
return this.save();
}
module.exports = mongoose.model('Product', productSchema);
Comments
Post a Comment