-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongooseModels.js
87 lines (81 loc) · 1.69 KB
/
mongooseModels.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose';
const opts = { toJSON: { virtuals: true } };
const reviewSchema = mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
body: {
type: String,
required: true,
},
rating: {
type: Number,
required: true,
},
});
const imageSchema = mongoose.Schema({
url: String,
filename: String,
});
imageSchema.virtual('thumbnail').get(function () {
return this.url.replace('/upload', '/upload/w_200');
});
const campgroundSchema = mongoose.Schema(
{
title: String,
price: Number,
images: [imageSchema],
geometry: {
type: {
type: String,
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
required: true,
},
},
description: String,
location: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
reviews: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Review',
},
],
},
opts
);
campgroundSchema.virtual('properties.campLink').get(function () {
return `<a href= /campgrounds/${this._id}>${this.title}</a>`;
});
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
});
// middlewares
userSchema.plugin(passportLocalMongoose);
campgroundSchema.post('findOneAndDelete', async function (camp) {
if (camp) {
Review.deleteMany({ _id: { $in: camp.reviews } });
}
});
const User = mongoose.model('User', userSchema);
const Review = mongoose.model('Review', reviewSchema);
const Campground = mongoose.model('Campground', campgroundSchema);
export { Campground, Review, User };