MongoDB and Mongoose - Create and Save a Record of a Model

Hello Everyone, I feel like this particular exercise was explained horribly and it’s vital for continued understanding in future exercises so I figured I would try and shed some light

so forgive me but I personally think this should’ve been taught with promises and should probably be updated to do so. Any it’s functionally doing the same thing as a callback. I more so just want to explain what’s happening for the very (and rightfully so) confused beginners here.
Your code so far

so I feel like I can skip over the instantiations of the schema and model pieces since that seems to be fairly well understood and get to the meaty part

./myApp.js
const createAndSavePerson = (done) => {
let antz = new Person({name: “Antz”, age: 34, favoriteFoods: [“Pizza”, “Mango”, “Salmon”]});
antz.save()
.then((data) => {return done(null, data)} )
.catch((err) => {return done(err)});
};

it’s VERY important to look at and understand ./server.js for this, not sure why that wasn’t brought to attention

./server.js
const createPerson = require(“./myApp.js”).createAndSavePerson;
router.get(“/create-and-save-person”, function (req, res, next) {
// in case of incorrect function use wait timeout then respond
let t = setTimeout(() => {
next({ message: “timeout” });
}, TIMEOUT);
createPerson(function (err, data) {
clearTimeout(t);
if (err) {
return next(err);
}
if (!data) {
console.log(“Missing done() argument”);
return next({ message: “Missing callback argument” });
}
Person.findById(data._id, function (err, pers) {
if (err) {
return next(err);
}
res.json(pers);
//pers.remove();
});
});
});

Okay, phew … So what you need to know is that your createAndSavePerson function defined on the const variable in ./myApp.js HAS to be called, like all functions. That function gets EXPORTED at the bottom of it’s module(file) and then required in ./server.js where it is assigned to a new variable called createPerson.
createPerson then gets called in ./server.js as createPerson(function(err, data){…stuff}).
That function call is actually the call to the original createAndSavePerson(done) in ./myApp js, so the function inside of createPerson()'s brackets IS the done(null/err, data) function being passed into the the createAndSavePerson(done) function in ./myApp.js. This is why you are calling that callback inside of createAndSavePerson(done){ …here… } when you are calling save() on your model instance — done(null, data) means success because function(err, data) (from ./server.js) has two parameters and no error will be passed to done() if it succeeds, on the other hand ONLY an error will be passed if the call is not successful and therefore needs only one positional argument done(err).

So finally, I don’t know about everyone else but I’m using a local installation of mongoDB and not going through replit or whatever it is so I don’t know how it handles the API endpoints for you. Nonetheless as a final point, like I said every function HAS to be called eventually and Router() isn’t particularly explained here… ./server.js sets up a router.METHOD on GET call to an API endpoint of “/create-and-save-person”, this endpoint has to be accessed in one way or another to trigger your function call and start the entire process we’ve just went over. However without basic understanding of Router() it’s easy to not understand that these create modular routes that need to be wired into your express() app instance with app.use() which you find at the bottom of ./server.js in the following code.

app.use(“/_api”, enableCORS, router);
*what this means is that if you were to visit 127.0.0.1:3000/_api/create-and-save-person you will trigger the call to createPerson(function(err,data)) in ./server.js which will pass it’s internal function to done() inside of createAndSavePerson(done) in ./myApp.js and then return either data or err based on the success or failure of your save() operation. Which if on success will return to you a json response of your save()'ed data in your browser page and will be accessible for you retrieve from your mongo DB to verify it truly did save

I’m genuinely sorry if that was confusing but I tried to elaborate in the most clear and concise way possible, have a good day y’all —cheers

Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36

Challenge: MongoDB and Mongoose - Create and Save a Record of a Model

Link to the challenge:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.