-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseedDatabase.js
More file actions
90 lines (82 loc) · 2.02 KB
/
Copy pathseedDatabase.js
File metadata and controls
90 lines (82 loc) · 2.02 KB
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
88
89
90
const sampleData = require('./data/sampleData');
const mongoose = require('mongoose');
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost/silverspoon';
mongoose.connect('mongodb://mongo/silverspoon');
const restaurantSchema = mongoose.Schema({
id: { type: Number, unique: true },
name: String,
menu: {
lunch: [{
foodItem: String,
cost: Number,
tags: String,
}],
dinner: [{
foodItem: String,
cost: Number,
tags: String,
}],
dessert: [{
foodItem: String,
cost: Number,
tags: String,
}],
},
}).index({ name: 1 });
const Restaurant = mongoose.model('restaurantMenus', restaurantSchema);
// Restaurant.init().then(() => mongoose.disconnect());
const save = (options, cb) => {
const { data } = options;
const Model = options.model;
let count = 0;
const idArr = [];
data.forEach((item) => {
const instance = new Model({
id: item.id,
name: item.name,
menu: {
lunch: item.menu.lunch,
dinner: item.menu.dinner,
dessert: item.menu.dessert,
},
});
if (!idArr.includes(item.id)) {
idArr.push(item.id);
Model.create(instance, (err, result) => {
count += 1;
if (err) {
console.log('ERR: duplicate title already found in collection');
}
if (count === data.length) {
cb(result);
}
});
} else {
count += 1;
}
});
};
const find = (options, cb) => {
const query = options.query || 'menu.lunch';
const name = options.name || 'restaurant15555555';
if (query === '{}') {
Restaurant.findOne({ 'name': name }).exec((err, data) => {
if (err) {
cb(err, null);
} else {
cb(null, data);
}
});
} else {
Restaurant.findOne({ 'name': name }).select(query).exec((err, data) => {
if (err) {
cb(err, null);
} else {
cb(null, data);
}
});
}
};
module.exports.save = save;
module.exports.find = find;
module.exports.Restaurant = Restaurant;