I am trying to display the details of the documents inserted in PouchDB with
var docs = db.allDocs({include_docs: true}, function(err, response) {
}
but this does not seem to display the details of the document. Thew display is as shown below
{ total_rows: 6,
offset: 0,
rows:
[ { id: 'book1', key: 'book1', value: [Object], doc: [Object] },
{ id: 'book2', key: 'book2', value: [Object], doc: [Object] },
{ id: 'book3', key: 'book3', value: [Object], doc: [Object] },
The value and doc is still shown as objects. The code is included below. I am not sure what I am missing. Please let me know.
var docs = db.allDocs({include_docs: true}, function(err, response) {
var val = response.total_rows;
var value = "";
res.writeHead(200, {'Content-Type': 'text/plain'});
for(i=0; i < val; i++) {
console.log(JSON.stringify(response.rows[i].id) + "\n");
res.write(JSON.stringify(response.rows[i].id) + "\n")'
}
res.end();
});
You should have a look into the doc property of each row in rows.
You should also notice, that total_rows give you the number of all docs in the db even if you limit the documents with startkey and / or endkey. You better use the forEach method of the array prototype.
Related
I'm very new to JS, and what I'm trying to do is create a new array that filters out elements in an existing array that have a null value. In my example code below, I would want to create a new array that filters out the third item because the url is an empty string (I only want it to filter based on whether the url is an empty string). I should add that the const is being exported as part of a reducer, and in the file it's actually used in, we're calling on {props.categories}. Any help is greatly appreciated!!!
const categories = () => {
return [
{
id: 0,
title: "Google",
url: "www.google.com",
},
{
id: 1,
title: "Firefox",
url: "www.firefox.com",
},
{
id: 2,
title: "Placeholder",
url: "",
},
];
};
Arrays have a filter function that takes a function to return true/false if the current element should be filtered through to the result array.
const categories = [
{
id: 0,
title: "Google",
url: "www.google.com",
},
{
id: 1,
title: "Firefox",
url: "www.firefox.com",
},
{
id: 2,
title: "Placeholder",
url: "",
},
];
const filterBlankUrl = arr => arr.filter(({ url }) => !!url);
const filteredCats = filterBlankUrl(categories);
console.log(filteredCats);
Thanks so much everyone for your help! I did actually finally figure it out; in the file where I was actually referencing the array, I needed to update the code to this:
options={props.categories.filter(categories => categories.url !== "")}
This is my api:
exports.getService = function(req, res) {
var limit = 10; // number of records per page
var offset = 0;
Service.findAndCountAll({
raw: true,
where: {
shop: req.user.shop
}
}).then((data) => {
var page = req.params.page; // page number
var pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
Service.findAll({
// raw: true,
limit: limit,
offset: offset,
$sort: {
id: 1
},
where: {
shop: req.user.shop
},
include: [{
model: Categoryservice,
attributes: ['id'],
include: [{
model: Category,
attributes: ['id', 'name'],
}]
}],
}).then(function (services) {
var services=JSON.parse(JSON. stringify(services));
console.log('=====stringify==========>>',services);
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
}).catch(function(error) {
res.status(500).send('Internal Server Error');
});
};
I am using map in last then fuction ,
It contains a error map undefined in the server..
I want want a out like below given json using the map fuction.
Actually i need this out put:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [
1,
2
]
}
my JSON. stringify(services) out put is:
=====stringify==========>> [ { id: 2,
username: null,
name: null,
image: null,
service: 'mobile',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '20',
per: '10',
tax: '1',
activity: null,
createdAt: '2018-03-14T07:30:57.000Z',
updatedAt: '2018-03-14T07:30:57.000Z',
categoryservices: [ [Object], [Object] ] },
{ id: 1,
username: 'sam',
name: 'New Service',
image: '/images/uploads/22-Feb-2018/f96334384cd78754454c5e4e05e20fc0-dragon_pattern_red_black_9666_1920x1080.jpg',
service: 'battery',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '5',
per: '1',
tax: '1',
activity: '2018-03-14T06:01:36.000Z',
createdAt: '2018-03-14T06:01:36.000Z',
updatedAt: '2018-03-14T06:01:36.000Z',
categoryservices: [] } ]
I was beginner of using map function,
so,I am confused in map ,
so please give any solution to this problem.
You are stringifying your array that comes back. You can't do that if you plan to use .map on it. Remove that code and try again.
.then(function (services) {
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
I think we are missing something because the output you pasted doesn't have the category.id attribute that you are returning from the item passed in to map. Is that what you are trying to target? That's off topic, but this code may not work for what you are trying to achieve but will run the map though.
Looks like services is an array, based on the console.log. If you want the id's of all categories, you can do
let categoryIds = [];
categoryIds = services.reduce((categoryIds, service) => {
let ids = service.categoryservices.map(category => category.id);
for(let id of ids) {
if(categoryIds.indexOf(id) === -1) {
categoryIds.push(id)
}
}
return categoryIds;
}, categoryIds);
If you want to have category ids as cats in each service, you can do,
var services=JSON.parse(JSON. stringify(services));
services.forEach(service) => {
service.cats = service.categoryservices.map(category => category.id);
delete service.categoryservices;
});
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
Hope this helps!
This is the model I am working with:
name: {
type: String
},
payment: {
id: {
type: String,
required: true
},
cards: [
{
id: {
type: String
},
is_default: {
type: Boolean,
"default": false
}
}
]
}
I want to add a card to the cards array, for example:
card =
id: "some_token"
is_default: true
I am using the update method to push the card to the array, but it won't add the card to the document. Instead, it creates a new document with only those fields:
{
id: "some_token",
is_default: true,
_id: someId
}
Any idea how I can update the actual document I am targeting instead of creating a new document?
Here's my code (using CoffeeScript):
update_where =
payment:
id: "some_id"
update_push =
$push:
'payment.cards':
id: card_token
is_default: false
Customer.update update_where, update_push, {upsert: true}, (err, results) ->
# Do something with the results
Oh… I just noticed my mistake. The problem was in the where statement.
I was doing:
payment:
id: "some_id"
But the right thing to write is the following:
'payment.id': 'some_id'
And it now works!
In my application I'm having the bellow problem
SERVER RESPONSE DATA
route /users
{ data: [
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
] }
route /users/5
{ data: { id: 5, name: 'peter' } }
case01
Restangular.one('users', 5).get().then(function(user){
$scope.user = user;
});
case02
Restangular.all('users').getList().then(function(users){
$scope.user = users[0];
});
In my case02 I can access $scope.user.id, but in case01 I have that to do $scope.user.data.id (what's not preferible when I render this in my template with {{ user.id }} where I have that use {{ user.data.id }} )
In my case02 I can change my data and use $scope.user.save(), but in my case01 I can't access this function
In my restangular I configure this for handle data from server when I use getList because it come in one object and not in one Array
RestangularProvider.setResponseInterceptor(function(response, operation, what) {
if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
});
So I would not work, because then I will have a normal JS object and not a Restangular object, the Restangular object has several methods that I still intend to use the same $scope, so we would like to preserve this.
example:
In an item from a case02 consultation (array) I have an object with methods of Restangular:
all (), allUrl (), one (), oneUrl (), ... and the properties of the object I sought (id, name) within $ scope.user.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
id: data_from_user,
name: data_from_user
}
In an item from a case01 query (object) I have an object with methods of Restangular within $ scope.user and object properties that sought (id, name) within $ scope.user.data.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
data: {
id: data_from_user,
name: data_from_user
}
}
For this reason it would not work the solution you presented because it is okay to work with restangular the subject, not an object of normal JS, but thank you for the answer Tim Castelijns.
if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
If operation is getList, you return response.data, which is
[
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
]
but if operation is not getList, you return response, which is the entire object, including the data sub-object
{
data: {
id: 5,
name: 'peter'
}
}
Your choice to return different results depending on what operation it is, is the reason you need to do user.data.id for case01, because you assign the result to user with then(function(user), when in fact user represents the entire data sub-object containing the user.
You should be able to solve it by changing to this
Restangular.one('users', 5).get().then(function(response){
$scope.user = response['data'];
});
I have a Kendo Scheduler on my page.
<div kendo-scheduler k-options="schedulerOptions" k-data-source="items"></div>
My angular controller will make a call to the server to get data, it looks like this, but I do not know what my URL parameter will be until it loads up ($scope.$watch).
$scope.$watch(function () { return MyService.leadID; }, function (newValue) {
if (newValue) {
getAppointmentsTabData(newValue);
}
});
var getAppointmentsTabData = function (leadID) {
MyService.getAppointmentsTabData(leadID)
.then(function (data) {
$scope.items = data;
}
}
);
};
How can I bind this data to my Kendo Scheduler?
I can get this Scheduler to work with static data, but not the JSON list of objects that get returned when the server sends them. I would like to be able to bind my $scope.items to the dataSource, but that does not appear to work.
Here is the schedulerOptions code.
$scope.schedulerOptions = {
date: new Date("2014/10/13"),
startTime: new Date("2014/10/13 07:00 AM"),
height: 310,
views: [
"agenda",
{ type: "week", selected: true, allDaySlot: false },
{ selectedDateFormat: "{0:dd-MM-yyyy}" }
],
eventTemplate: "<span class='custom-event'>{{dataItem.title}}</span>",
allDayEventTemplate: "<div class='custom-all-day-event'>{{dataItem.title}}</div>",
timezone: "Etc/UTC",
dataSource: {
data: $scope.items,
schema: {
model: {
id: "id",
fields: {
id: { from: "ID", type: "number" },
appointmentId: { from: "AppointmentId", type: "number" },
resource: { from: "Resource", type: "number" },
description: { from: "Description" },
isAllDay: { type: "boolean", from: "IsAllDay" },
end: { from: "End", type: "date" },
start: { from: "Start", type: "date" },
title: { from: "Title", defaultValue: "No title" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
}
}
},
}
};
I can get the static approach to work. I cannot really use the remote data approach that looks like this (below) because I do not know what my URL is until my $scope.$watch is triggered. I need to append query string params.
dataSource: {
batch: true,
transport: {
read: {
url: "/MyController/GetMyData",
dataType: "json",
},
Does anyone have any suggestions on how I can populate my Scheduler dataSource dynamically?
I have seen this question, Kendo update scheduler options dynamically, but I am not having any luck getting the setOptions(). If only I could call $scope.myScheduler.setOptions("dataSource", myJsonObjectArry), that would be awesome, but nothing.
I am able to manipulate $scope.myScheduler._data (as an array), but I need some form of a refresh method to redraw my UI. This approach doesn't seem right though.
Thanks for any help.
I am answering my own question. In case you run into this situation, here is how I solved it.
Here is my schedulerOptions now. Notice there is no dataSource set and no schema. This is because I will populate that with my own dataSource dynamically.
$scope.schedulerOptions = {
date: new Date("2014/10/13"),
startTime: new Date("2014/10/13 07:00 AM"),
showWorkHours: true,
height: 310,
views: [
"agenda",
{ type: "week", selected: true, allDaySlot: false },
{ selectedDateFormat: "{0:dd-MM-yyyy}" }
],
edit: $scope.edit,
editable: {
template: $("#editor").html()
},
timezone: "Etc/UTC",
dataSource: {
data: [], // will be set dynamically
}
};
When my data is returned to this js controller, I will call this.
$scope.myScheduler.dataSource.data(getSchedulerEvents($scope.data.items));
Which in turn will call this, which creates the dataSource for me.
var getSchedulerEvents = function (items) {
var result = [];
var event;
for (var i = 0, length = items.length; i < length; i++) {
event = items[i];
result.push(new kendo.data.SchedulerEvent({
id: event.ID,
title: event.Title,
description: event.Description,
start: kendo.parseDate(event.Start),
end: kendo.parseDate(event.End),
isAllDay: event.IsAllDay,
recurrenceException: event.RecurrenceException,
recurrenceId: event.RecurrenceId,
recurrenceRule: event.RecurrenceRule,
resource: event.Resource,
}));
}
return result;
}
If you run into this problem, hopefully this helps.