Welcome, stargazers! Today, we're venturing into the realms of creating and updating data in MongoDB. It bears a resemblance to a space diary, where you log observations of new celestial objects and note changes in their properties over time.
Our data logbooks in MongoDB are referred to as documents
. Have you discovered a new star? Let's create a log entry, or document
, for it:
JavaScript1const mongoose = require('mongoose'); 2const starSchema = new mongoose.Schema({ 3 name: String, 4 constellation: String, 5 magnitude: Number 6}); 7const Star = mongoose.model('Star', starSchema); 8 9async function insertStar() { 10 await mongoose.connect('mongodb://127.0.0.1/myDB'); 11 const star = new Star({ 12 name: "Polaris", 13 constellation: "Ursa Minor", 14 magnitude: 2.0 15 }); 16 const result = await star.save(); 17 console.log(result); 18 mongoose.connection.close(); 19} 20 21insertStar();
Here, we created a star
object instance from the Star
model using the new Star
call and saved it into the database with the save()
async method. Simple, isn't it?
At the end of the function, we called mongoose.connection.close();
. This line closes the current connection to the MongoDB server. This helps in freeing up system resources that our application was using during the connection. It's a good practice to close unnecessary connections especially when the DB operations are no longer required or when all the tasks are finished. This maintains optimal application performance and prevents memory and connection leaks.
For multiple discoveries, we can log them all at once using insertMany()
:
JavaScript1async function insertStars() { 2 await mongoose.connect('mongodb://127.0.0.1/myDB'); 3 const stars = [{ 4 name: "Sirius", 5 constellation: "Canis Major", 6 magnitude: -1.46 7 },{ 8 name: "Canopus", 9 constellation: "Carina", 10 magnitude: -0.74 11 },{ 12 name: "Arcturus", 13 constellation: "Boötes", 14 magnitude: -0.04 15 }]; 16 const result = await Star.insertMany(stars); 17 console.log(result); 18 mongoose.connection.close(); 19} 20 21insertStars();
After each insert operation, MongoDB provides a response, acknowledging the operation's successful completion.
Data logging isn't limited to discovery; data needs to be updated based on new observations. For this, Mongoose provides the findOne()
and save()
.
Assuming the magnitude of Polaris has been updated from 2.0 to 2.02, we can reflect this new observation in our MongoDB database:
JavaScript1async function updateStar() { 2 await mongoose.connect('mongodb://127.0.0.1/myDB'); 3 const star = await Star.findOne({ name: "Polaris" }); 4 if (!star) { 5 console.log('Star not found.'); 6 return; 7 } 8 star.magnitude = 2.02; 9 const result = await star.save(); 10 console.log(result); 11 mongoose.connection.close(); 12} 13 14updateStar();
We fetch the document using findOne(), modify the magnitude, and save back to the database.
Congratulations, stargazers! We now understand how to add new documents to our MongoDB collection and modify the existing ones using save()
and insertMany()
. What's the next stage? Engaging practice exercises. Remember, practice makes perfect and solidifies these concepts in our memory. Keep exploring, keep learning, and most importantly, enjoy the journey! Happy coding!