Step 9
The create
method attached to a Mongoose model is, as you expect, an async operation. We embraced the callback pattern to deal with it. We can try the alternative patterns:
Promise Pattern: rewrite the User.create(...)
as follows.
User.create({
username: faker.internet.userName(),
password: faker.internet.password(),
})
.then((user) => {
console.log(user);
})
.catch((err) => {
console.log(err);
});
Save index.js
and run the application. A new user document must be printed to the terminal. Go to Atlas website and click on "Refresh" button to see the new user added to the database.
Async/Await Pattern: rewrite the User.create(...)
as follows.
async function createUser(username, password) {
try {
const user = await User.create({
username,
password,
});
console.log(user);
} catch (err) {
console.log(err);
}
}
createUser(faker.internet.userName(), faker.internet.password());
Save index.js
and run the application. A new user document must be printed to the terminal. Go to Atlas website and click on "Refresh" button to see the new user added to the database.
The data is randomly created so your users will have different username and password compared to what you see in the image here.