how to get length of couch.get(data,headers,status) - json

I tried to create nodejs with expressjs by connecting to couchdb . For that I have used nodejs-couch installed using npm.
app.get('/', function(req, res) {
couch
.get(dbName, viewUrl)
.then(
function(data, headers, status) {
console.log(data.length);
var data1 = data.data.rows;
console.log(data1);
res.send(data1.length);
},
function(err) {
res.send(err);
}
);
});
my json data :
[
{
"id": "7a6a4d9cf76efc00977ca63ca3002a31",
"key": "7a6a4d9cf76efc00977ca63ca3002a31",
"value": {
"name": "nagarjuna",
"email": "nagarjuna#gmail.com",
"password": "12345",
"mobile": "987654321",
"rev": "8-c90103f1fca709ae314a684c767c97dc"
}
},
{
"id": "7a6a4d9cf76efc00977ca63ca3003743",
"key": "7a6a4d9cf76efc00977ca63ca3003743",
"value": {
"name": "sandeep",
"email": "sandeep#gmail.com",
"password": "54321",
"mobile": "9876541",
"rev": "1-fd6e667b87794adea78e169bc46016e6"
}
}
]
I had written get function to fetch all customer information. If I print console.log(data.data.rows); I am able fetch json data. But I want to get length and attribute values from json. But when I print console.log(data.length); it getting undefined.
Can any one suggest me. Any suggestions would be appreciated.

The result from the database contains a lot of different information, like meta information and the results. Here is a trimmed down representation of what you're looking for
var data = {
data: {
rows: [{row1},{row2}...];
}
}
So for you to be able to get the length of rows from the database, you'll have to dig into the right attribute in the object like this:
var length = data.data.rows.length;

Related

getting data from an array of objects inside array JSON data

I have trouble taking data from an API set. The body if viewed in Postman / Insomnia is as follows
{
"responses": {
"log": [
{
"id": 123,
"date": "2022-01-01T01:12:12.000Z",
"type": "online",
"details": [{
"detailId": "123-1",
"note": "success",
}]
},
{
"id": 124,
"date": "2022-01-01T01:12:12.000Z",
"type": "offline",
"details": [{
"detailId": "123-2",
"note": "failed",
}]
}
]
}
}
I want to take all data from log, as well from details. I used
adapt(item: any) {
return {
id: item.id,
date: item.date,
details: {
detailId: item.details.detailId,
note: item.details.note,
},
};
}
this returns id and date just fine. I also have a query to filter it based on type (online or offline), basically adding &type= into the API. It works for the online, but it returns detailId is undefined for offline (I used the same body, adapter and API minus the query for both data)
details is an array of object if you want to adapt it you need to do it iteratively.
adapt(item: any) {
const details = item.details.map(d => {detailId: d.id, note: d.note, …});
return {
id: item.id,
date: item.date,
details
};
}
Found the answer, apparently to make sure that I can get every value is to add ? after the [0], so it should be
details: {
detailId: item.details[0]?.detailId,
note: item.details[0]?.note,
},

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.

couchdb ; how get documents directly in first level of json, and not grouped inside value - viewWithList

I have a design document: 'accounts',and the view: 'accounts-view'
the view's content is:
function (doc) {
emit( doc._id, doc);
}
And my code in express is:
db.view('accounts', 'accounts-view', function(err, body) {
if (err) throw error;
res.json(body.rows);
});
Result is:
[
{
"id": "8767d3474a0e80dd0ab7d0b0580065af",
"key": "8767d3474a0e80dd0ab7d0b0580065af",
"value": {
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
}
},
{
"id": "8767d3474a0e80dd0ab7d0b058006e3c",
"key": "8767d3474a0e80dd0ab7d0b058006e3c",
"value": {
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
}
}
]
How i can get just something like this: ( just printing all is inside value for every row)
[
{
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
}
]
UPDATE:
I've follow Domonique's suggestions ; and now I have a new view, that emit just the id (so i can save space on disk and retrive de doc with the parameter "include_docs=true" on the view):
function(doc) {
if (doc.type && doc.type=='accounts') {
emit( doc._id);
}
}
and a new list:
function(head, req) {
provides('json', function() {
var results = [];
while (row = getRow()) {
//results.push(row.value);
results.push(row.doc);
}
send(JSON.stringify(results));
});
}
Finally i get the records with:
http://127.0.0.1:5984/crm/_design/crmapp/_list/accounts-list/accounts-view?include_docs=true
and the result is:
[
{
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058008e9a",
"_rev": "1-86078f00be82b97499a0f52488cefbbf",
"lastname": "Tower",
"firstname": "George",
"type": "accounts"
}
]
my app node express updated:
db.viewWithList('crmapp', 'accounts-view','accounts-list', {"include_docs":"true"} , function(err, body) {
if (err) throw err;
res.json(body);
});
with this list , I don't need more reduce it on express project, it's ok ?
How to udate my list or view to get by id ? it'not working just adding id on the url ; like this:
http://127.0.0.1:5984/crm/_design/crmapp/_list/accounts-list/accounts-view?include_docs=true&_id=8767d3474a0e80dd0ab7d0b058006e3c
I get all the records and not the only one by id
To answer your question here, you should simply map the array and only include the value portion:
db.view('accounts', 'accounts-view', function(err, body) {
if (err) throw error;
res.json(body.rows.map(function (row) {
return row.value;
}));
});
Since it's apparent you are new to CouchDB, I'll also give you some advice regarding views. First, the view you've created is actually just a duplicate of the system view _all_docs, so you should just use that instead rather than creating your own view. (especially since you've effectively created a duplicate on disk)
However, it is probably pretty likely that as you get further along in your application, you'll be using real views that partition documents differently depending on the query. As such, you should not emit your entire document (ie: doc) in your view function. By doing this, you are effectively duplicating that document on disk, since it will be represented in your database, as well as the view index.
The recommended starting point is to simply leave out the 2nd argument of your emit.
function (doc) {
emit(doc._id);
}
When you query the view, you can simply add include_docs=true to the URL and your view will look something like this:
[
{
"id": "8767d3474a0e80dd0ab7d0b0580065af",
"key": "8767d3474a0e80dd0ab7d0b0580065af",
"value": null,
"doc": {
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
}
}
// ...
]
Then, you can retrieve the doc instead of value to achieve the same result much more efficiently.

How to return a subcollection (or object) in json without including all attributes

I am using mongoose as JSON Schema and node.js with it. Need not say, I am new to both. I have been struggling through the day to get this thing work for me but couldn't. Finally, the only solution was to get help from some real nice people out here.
Here is my schema definition -
UserName = {
"properties": {
userURL: {
"description": "URL of this resource",
"type": "string"
},
userName : {
"description": "UserName",
"type": "string",
"required": true
},
}
}
When I make a get call to it, it returns the response in following format -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"__v": 0,
"properties": {
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
}
]
Now my requirement is to return the response in following format -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
]
i.e without version and properties tags. I am able to get away with version using following code but properties seems to be tricky thing -
.get(function(request, response) {
UserSchemaModel.find().select('properties.userURL properties.userName').exec (function (err, resObj) {
if (err)
response.send(err);
else{
response.json(resObj);
}
});
});
But it still has properties field :( -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"properties": {
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
}
]
I did some google around select as, alias name in select,population in mongoose but no luck.
Kindly suggest. With best Regards.
Just make a new object
response.json(
{
"_id": resObj["_id"],
"userURL": resObj["properties"]["userUrl"],
"userName": resObj["properties"]["userName"]
}
);
Update: Since resObj is an array (as per your comment), you can use Array.prototype.map() to transform them into the right format like so:
response.json( resObj.map(function(o){
return {
"_id": o["_id"],
"userURL": o["properties"]["userUrl"],
"userName": o["properties"]["userName"]
};
})
);
This will return a list of transformed objects that then get passed into the response.json() method.

Extracting json object and filling in user label

[{"id":1,"name":"ABC"},{"id":2,"name":"XYZ"}]
This is how the data is returned by the controller in json format
I want to store it in the following format:
var json = {
"users": [
{ "id": "1", "name": "ABC" },
{ "id": "2", "name": "XYZ" },
]
}
Following is the code I have used but doesnt work.
var json =
{
"users": $.getJSON("#Url.Action("SearchCMSAdmins")")
}
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate:json.users
});
Any help is appreciated. Thanks in advance.
$.getJson is asynchronous, so you need to use the success callback for getting the response and doing the operation. Try this INstead.
$.getJSON("#Url.Action("SearchCMSAdmins")",function(data){
var json= {"users":data};
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate:json.users
});
});