-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.js
84 lines (70 loc) · 2.08 KB
/
update.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
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);
// UPDATE
await updateListingByName("Jennny", { name: "Jen" });
await findOneListingByName("Jen");
// UPSERT
await upsertListingByName("Jenny", { name: "Jen" });
await findOneListingByName("Jenny");
// UPDATE MANY
await updateAllListingsToHavePropertyType();
await findAllListing();
} catch (error) {
console.log(error);
}
}
main();
async function updateListingByName(nameOfListing, updatedListing) {
const result = await User.updateOne(
{ name: nameOfListing },
{ $set: updatedListing }
);
console.log(`${result.matchedCount} document(s) matched the query criteria.`);
console.log(`${result.modifiedCount} document(s) was/were updated.`);
}
async function upsertListingByName(nameOfListing, updatedListing) {
const result = await User.updateOne(
{ name: nameOfListing },
{ $set: updatedListing },
{ upsert: true }
);
if (result.upsertedCount > 0) {
console.log(`One document was inserted with the id ${result.upsertedId}`);
} else {
console.log(`${result.modifiedCount} document(s) was/were updated.`);
}
}
async function updateAllListingsToHavePropertyType() {
const result = await User.updateMany(
{
tel_no: { $exists: false },
},
{
$set: { tel_no: "" },
},
{
strict: false,
}
);
console.log(`${result.matchedCount} document(s) matched the query criteria.`);
console.log(`${result.modifiedCount} document(s) was/were updated.`);
}
async function findAllListing() {
const results = await User.find();
console.log(results);
}
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}'`);
}
}