Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Now, to create a user, the first thing to do is to create a resource:


const user_resource = new User({
name: 'John Doe',
email: '[email protected]'
})

Now, finally, the part that actually creates the user is:


user_resource.save((error) => {
if(error)
console.log(error);

res.send({
success: true,
code: 200,
msg: "User added!"
})
})

The previous code uses a Mongoose function called save. The save method has a callback


function that is used for error handling. We can do whatever we want when we encounter


an error while saving the resource to our database there:


user_resource.save((error) => {
if(error)
console.log(error);

res.send({
success: true,
code: 200,
msg: "User added!"
})
})

The res.send method allows us to set what we want to send to the client when the


resource is successfully saved to the database. The first element of the object is success:


true, which denotes if the execution was successful or not. The second element is the status


code or the response code. A 200 response code denotes successful execution. We will


discuss this in further chapters as well.The last element is the message that is sent to the


client; the users see this in the frontend.


That's how we create a resource in Mongoose.

Free download pdf