After adding the users to the users collection, we also can update them using the same code structure as in the previous section in the following steps:
- Create a route with the put method for updating the existing user document as follows:
// server/routes.js
router.put('/user', async (ctx, next) => {
let result
//...
})
- Before updating a document, we want to make sure the slug value is unique. So, inside the put route, we search for a match with the findOne API with $ne to exclude the document that we are updating. If there is no match, then we go on updating the document with the updateOne API method:
const found = await collectionUser.findOne({
slug: body.slug,
_id: { $ne: mongo.objectId(body.id) }
})
if (found) {
ctx.throw(404, 'slug has been taken')
}
result = await collectionUser.updateOne({
_id: mongo.objectId(body.id)
}, {
$set: { name: body.name, slug: body.slug },
$currentDate...