Enhancing Couchdb documents with unique id and author information through an update handler

Is there a way to include additional fields using the update handler in Couchdb? I'm trying to insert the author (with a validation function to verify that the user is logged in) and the id when creating a new document via an update handler.

The author's name can be accessed from req.userCtx.Name, the data sent is in req.body, and I'm utilizing req.uuid as the _id

"updates": {
   "new": "function(doc,req) { var message = req.uuid; return [ { _id : req.uuid, "author" : req.userCtx.name, data : req.body}, message]}"
}

Data is being transmitted through a curl POST

$ cat test.json
{"data" : {"name" : "myname","dob" : "myDOB"}}

This is how the data appears when processed by the update handler

{"_id":"a018fed749d64f5db754b39af803a88f","_rev":"1-939793c36d2bfe4de86f808fab056959","author":"admin","data":"{\"name\" : \"myname\",\"dob\" : \"myDOB\"}"}

If I perform a standard POST (not via an update handler), the output looks like this:

{"_id":"a018fed749d64f5db754b39af803b621","_rev":"1-e44f0471e1df1018439fee3681b49547","data":{"name":"myname","dob":"myDOB"}}

What could be the error in my approach?


EDIT

After spending several hours searching and then posting questions, I finally found the solution.

Reference link -

{ "new": "function(doc,req) { var data = JSON.parse(req.body); data['_id'] = req.uuid;data.author = req.userCtx.name; message = req.uuid; return [ data, message]}" }

Now the document includes id and author information..

{"_id":"a018fed749d64f5db754b39af80406b7","_rev":"1-c486b02d6f320eb15e6115e71b3f02cc","data":{"name":"myname","dob":"myDOB"},"author":"admin"}

Answer №1

After spending a few hours searching and posting questions, I finally found the solution.

I came across this information on -

{
   "new": "function(doc,req) { 
        var data = **JSON.parse(req.body)**; 
        data['_id'] = req.uuid;data.author = req.userCtx.name; 
        message = req.uuid; 
        return [ data, message]
    }"
}

Now, the document contains an ID and author information.

{   "_id":"a018fed749d64f5db754b39af80406b7",
    "_rev":"1-c486b02d6f320eb15e6115e71b3f02cc",
    "data":{"name":"myname","dob":"myDOB"},
    "author":"admin"
}

Answer №2

If you want to improve your Update Handler function, consider having it return the Request object along with other data like shown in the code snippet below:

(...)
return [document, JSON.stringify(request)]
(...)

I made this adjustment in order to better understand and analyze the properties within the Request object. For more information on the Request object, refer to the documentation here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encounter the error "Attempting to access object using Object.keys on a non-object" when attempting to retrieve all fields in request.body in Node.js?

I am working with a piece of code that handles the PUT method: module.exports.addRoutes = function(server) { //PUT server.put('/api/public/place/:id', function(request, response) { //this is just for testing, please do not care ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

Debugging in Javascript involves pausing or breaking at every instance of a javascript function being called

I am currently working on unraveling a complex legacy JavaScript codebase, and I'm finding it challenging to determine where to place breakpoints (having to locate the files and set a breakpoint in Firebug, etc). Is there a way for Firebug to automat ...

Using a series of identical divs to dynamically update the image URL

Greetings! I am a newcomer to the world of web development and I have decided to hone my skills by creating a small website for my mother! My goal is to replicate a specific div multiple times while changing only the image URL and the heading caption. < ...

Expanding upon React Abstract Component using Typescript

Currently, I am in the process of building a library that contains presentations using React. To ensure consistency and structure, each presentation component needs to have specific attributes set. This led me to create a TypeScript file that can be extend ...

After transitioning my Image Modal from an ID to a Class, it appears to not be functioning properly

I recently implemented an image modal on my website using the ID attribute, but it didn't seem to work as expected. After changing the id to a class, now the image modal is not functioning at all and I'm struggling to figure out what went wrong. ...

Substitutions not functional when using SendGrid in conjunction with Firebase functions

I'm encountering difficulties when trying to include substitutions data in emails sent from Sendgrid using Firebase Cloud Functions. Here's my function exports.firestoreEmail = functions.firestore .document('users/{id}') .onCreate(s ...

Assign a class to the element only when the second div also has a class

I am trying to create a functionality where I have a dropdown element (Li element) that receives an Active class when its parent div (button) is clicked. When the dropdown element has this class, I want to assign the same class to another div. If the dropd ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

In an empty JavaScript MVVM Organization View, the ViewModel is packed with lines of code

I find myself always placing all of my code within the ViewModel because nothing else seems to fit. What kinds of things should be included in the view? Does anyone have any examples? ...

Navigation buttons that move the user either up or down the page

I am a beginner in programming and I wanted to create two buttons for my webpage. One button should appear when the page is scrolled more than 300px and take the user to the top, while the other button should be displayed immediately and scroll the user to ...

Steps to develop a log-in API using Node.js

In the process of developing my web application, I have utilized node js exclusively for all functionalities and the web user interface has been successfully implemented. An issue that has come to light is that users are able to access the services API wi ...

Tips for finding values using an array as the selector

I am working with a JSON document in my CouchDB that looks like this: { { "_id": "someid|goes|here", "collected": { "tags": ["abc", "def", "ghi"] } }, { "_id": "someid1|goes|here", "collected": { " ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

What's causing jQuery to make the entire page malfunction?

I am experiencing an issue where a function is not recognized as being in scope when I have a reference to jQuery defined. Oddly enough, if I comment out that reference, the function call works just fine. I have other pages set up the same way with jQuer ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

Trigger ng-change event for each dropdown selection made in AngularJS

Currently, I have a dropdown menu that allows users to select a report for generation. When a user picks a report from the dropdown, it generates and downloads the report for mobile viewing. By utilizing ng-change, the system only detects when a user wants ...

Is there a way to determine if a browser supports the offline event?

I attempted to implement the code from this Stack Overflow question: How can I check for support of the `focusin` event? However, in Chromium, the method hasEvent('offline') returns false even though it supports the `offline` event. Does anyone ...