Question: How can I fix this code? import mongoose from 'mongoose'; import 'dotenv / config ' ; const USER _ DB _ NAME = 'Users _
How can I fix this code?
import mongoose from 'mongoose';
import 'dotenvconfig;
const USERDBNAME 'Usersdb;
const USERCOLLECTION 'users';
const USERCLASS 'User';
let connection undefined;
let User undefined;
This function connects to the MongoDB server.
async function connect
try
await mongoose.connectprocessenv.MONGODBCONNECTSTRING;
connection mongoose.connection;
console.logSuccessfully connected to MongoDB using Mongoose!";
ifdropCollection
await connection.dbdropCollectionUSERCOLLECTION;
User createModel;
catcherr
console.logerr;
throw ErrorCould not connect to MongoDB $errmessage
function createModel
const userSchema mongoose.Schema
name: type: String, required: true
age: type: Number, required: true
email: type: String, required: true
phoneNumber: type: Number, required: false
;
return mongoose.modelUSERCLASS, userSchema;
async function createUsername age, email, phoneNumber
const user new Username: name, age: age, email: email, phoneNumber: phoneNumber;
return user.save;
async function findUsersfilter
const query User.findfilter;
return query.exec;
async function findUserByIdid
const user await User.findByIdid;
return user.exec;
async function updateUserid updates
try
Ensure updates only contains valid fields for the schema
const allowedFields name 'age', 'email', 'phoneNumber';
const filteredUpdates ;
Object.keysupdatesforEachkey
if allowedFieldsincludeskey && updateskey undefined
filteredUpdateskey updateskey;
;
if ObjectkeysfilteredUpdateslength
throw new ErrorNo valid fields to update";
Use updateOne to apply the updates
const result await User.updateOne
id: id
$set: filteredUpdates Use $set to update specific fields
runValidators: true Ensure updates adhere to the schema's validation rules
;
if resultmatchedCount
throw new ErrorNot found";
Return the updated document requires an additional query
const updatedUser await User.findByIdid;
return updatedUser;
catch error
throw new Errorerrormessage;
async function deleteUsersquery
try
Delete users based on the provided query
const result await User.deleteManyquery;
Return the count of deleted documents
return deletedCount: result.deletedCount ;
catch error
throw new ErrorError deleting users: $errormessage;
const deleteById async id
const result await User.deleteOneid: id ;
return result.deletedCount;
export connect, createUser, findUsers, findUserById, updateUser, deleteUsers, deleteById ;
These are the directions:
Introduction
In this assignment, you will write a REST API for a collection of users. The REST API will store its data in MongoDB and will use Mongoose for interacting with MongoDB.
Instructions
Write a REST API that models a user and provides CRUD operations listed below.
You must write code in the files usersmodel.mjs and userscontroller.mjs to implement the REST API.Do not change any other files we have provided you in the starter code and do not add any new files to your app.
The user collection in MongoDB must be named users.
Your model code must be separate from your controller code.
The controller code must not directly call any Mongoose code, but can only interact with the database by calling functions exported by your model code. You cannot import the Mongoose package in the controller.You cannot import the express package in your model. You cannot pass any Express objects eg request and response to functions in your model.You cannot export the model class by default, Users from your model.
Your code must use the async and await syntax for asynchronous programming and cannot use the then syntax.
The route handler functions in the controller will be asynchronous. You must wrap these functions inside asyncHandler to prevent your Express server from crashing due to any uncaught exception.
Create using POST users
Request
Path parameter: None.Body: The body will be a JSON object with the following properties. You can assume that the body of a POST request will always be valid.
Response
Body: A JSON object with all properties of the newly created user, including idContenttype: applicationjsonStatus code:
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
