-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (56 loc) · 2.02 KB
/
index.js
File metadata and controls
70 lines (56 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
//Import mongoose
const mongoose = require('mongoose');
//Connect mongoose
//Connecting command('access url/ DBname'),{avoid deprecation warnings}
mongoose.connect('mongodb://localhost:27017/kaiwalyaKart', {useNewUrlParser: true, useUnifiedTopology: true});
//Check if the there was any error while connecting
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('We are connected!!');
});
//Creating schema - It is like a structure in which we will add document
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
});
//Passed a method to use later
studentSchema.methods.isAdded = function(){
const greeting = 'Student '+this.name+' of age '+this.age+' has been added sucessfully';
console.log(greeting);
}
//Compile entire schema into a single constant.
//Access name = method to access (collection name: schema to be compiled)
const student = mongoose.model('studentCollection', studentSchema);
//Creating new object of the comilled object.
const student1 = new student({
name: "Kaiwalya Koparkar",
age: 18
});
const student2 = new student({
name: "Ketan Koparkar",
age: 16
});
//Access the data provided with a new student locally
// console.log(student1.name);
// console.log(student1.age);
// student1.isAdded();
//---------------------------- Adding to DB (Create)---------------------------
//Saving the created document into the collection of DB.
student1.save(function(err, studentAdded){
if(err) return console.error(err);
studentAdded.isAdded();
});
student2.save(function(err, studentAdded){
if(err) return console.error(err);
studentAdded.isAdded();
});
//---------------------------- Finding in DB (Read) ---------------------------
student.find(function(err, studentInDB){
if(err) return console.error(err);
console.log(studentInDB);
});
student.find({name: "Ketan Koparkar"}, function(err, studentInDB){
if(err) return console.error(err);
console.log(studentInDB)
});