-
Notifications
You must be signed in to change notification settings - Fork 0
/
read.js
67 lines (56 loc) · 1.58 KB
/
read.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
const mongoose = require("mongoose");
mongoose.set("strictQuery", false);
const User = require("./model/User");
console.log(User);
async function main() {
const db_url = "mongodb://localhost:27017/mongoose_test";
try {
// Connect to the MongoDB cluster
await mongoose.connect(db_url);
// Find the listing by name
await findOneListingByName("Jen");
// Find listings by city name
await findListingByCity("California");
// Find all the listings in between range of age
await findListingByAge(20, 30);
} catch (error) {
console.log(error);
}
}
main();
async function findOneListingByName(nameOfListing) {
const result = await User.findOne({ name: nameOfListing });
if (result) {
console.log(result);
} else {
console.log(`No listings found with the name '${nameOfListing}'`);
}
}
async function findListingByCity(nameOfListing) {
const results = await User.find({ city: nameOfListing });
if (results) {
console.log(results);
} else {
console.log(`No listings found with the city '${nameOfListing}'`);
}
}
async function findListingByAge(lowerlimit, upperLimit) {
const results = await User.find({
age: { $gte: lowerlimit, $lte: upperLimit },
});
if (results.length > 0) {
console.log(results);
results.forEach((result, i) => {
console.log(`
${i + 1}. _id: ${result._id}
Name: ${result.name}
City: ${result.city}
Age: ${result.age}
`);
});
} else {
console.log(
`No listings found within age ${lowerlimit} and age ${upperLimit}.`
);
}
}