Answer the question
In order to leave comments, you need to log in
How to handle update of user data in DB?
Just started to deal with mongo/mongoose.
At the moment, I was able to get all users, get a user by id, and add the user to the database.
I can't figure out how to update/modify a user when requesting PATCH (/users/:id)
Please tell me. I tried to do it, I looked at the methods in the documentation, but something did not work out.
And another question. How to learn how to properly handle errors in node.js. It's very confusing as it is with error handling.
const Koa = require("koa");
const mongoose = require("mongoose");
const bodyParser = require("koa-bodyparser");
const app = new Koa();
const Router = require("koa-router");
const router = new Router();
app.use(bodyParser());
mongoose.Promise = Promise;
mongoose.connect("mongodb://localhost/test", { useMongoClient: true });
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
default: "[email protected]"
},
cdate: Date,
mdate: Date,
displayName: {
type: String,
required: true,
default: "Anonimous"
}
});
const User = mongoose.model("User", userSchema);
const user = new User({
email: "[email protected]",
cdate: Date.now(),
mdate: Date.now(),
displayName: "user"
});
router.get("/users", async (ctx, next) => {
const users = await User.find({});
ctx.body = users.map(user => ({
name: user.displayName,
email: user.email
}));
});
router.get("/users/:id", async (ctx, next) => {
if (!mongoose.Types.ObjectId.isValid(ctx.params.id)) {
ctx.throw(404, "invalid Report id");
}
const user = await User.findById(ctx.params.id);
if (!user) {
ctx.throw(404, "User not found");
}
ctx.body = {
user: user.displayName,
email: user.email
};
});
router.post("/users", async (ctx, next) => {
try {
const user = User.create({
email: ctx.request.body.email,
displayName: ctx.request.body.displayName,
cdate: Date.now(),
mdate: Date.now()
});
} catch (err) {
ctx.throw(400, "Error...");
}
});
app.use(router.routes());
app.listen(3000);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question