Firebase realtime database pagination not working as expected [duplicate] - reactjs

I am trying to sort orders in descending and start after on particular key but its not working
nextAfter : -Mk4-n5BnVpwhum62n2g or any Key / _id
db record:
{
'-Mk4-n5BnVpwhum62n2g': {
_id: '-Mk4-n5BnVpwhum62n2g',
createdAt: -1632171667626,
name: 'abc'
},
'-Mk40Ko9DbSeMdjIpY4': {
_id: '-Mk40Ko9DbSeMdjIpY4',
createdAt: -1632171809831,
name: 'new '
}
}
trying query :
query = dbRef.orderByChild('createdAt').startAfter(nextAfter).limitToFirst(limit);

The startAfter() method accepts two parameters - the first is the relevant orderBy value and the second is the optional key of the last entry (for when multiple entries have the same value for the orderBy criteria). So to correctly paginate the reference, you need to pass the previous entry's createdAt value and its key.
const baseQuery = dbRef
.orderByChild('createdAt')
.limitToFirst(limit);
let pageCount = 0, lastChildOnPage = undefined;
const children = [];
while (true) {
const pageQuery = pageCount === 0
? baseQuery
: baseQuery
.startAfter(lastChildOnPage.createdAt, lastChildOnPage.key);
const pageSnapshot = await pageQuery.once('value');
pageSnapshot.forEach((childSnapshot) => {
children.push({ key: childSnapshot.key, ...childSnapshot.val() });
})
const newLastChildOnPage = children[children.length-1];
if (lastChildOnPage !== newLastChildOnPage) {
lastChildOnPage = newLastChildOnPage;
pageCount++;
} else {
break; // no more data
}
}
console.log(`Grabbed ${pageCount} page(s) of data, retrieving ${children.length} children`);

Related

PUSH id in order like add to cart

I created model schema for users and products with simple CRUD, my next project is my model schema order where I push my userId and projectId in the array in order.
this is the code that I created in the controller
module.exports.makeOrders = (reqBody) => {
let newOrder = new Order({
totalAmount : reqBody.totalAmount,
usersOrder.push({
userId : reqBody.userId,
project : reqBody.projectId
}),
})
return newOrder.save().then((order, error) =>{
if(error){
return false;
}
else{
return true;
}
})
}
and this is my route
router.post("/checkout", (req, res) => {
let data = {
userId : req.body.userId,
productId : req.body.productId
}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})
this is my model
const orderSchema = new mongoose.Schema({
totalAmount : {
type : Number,
required : true
},
purchasedOn : {
type : Date,
default : new Date
},
usersOrder :[
{
userId : {
type : String,
required : true
},
productId : {
type : String,
required : true
},
}
]
})
this is what I enter in postman
{
"totalAmount" : 1000,
"userId" : "62a9c46c4d15dc8157c375aa",
"productId" : "62aafe01d9337ce87ff5aaa1"
}
the error that I'm experiencing is "SyntaxError: Unexpected token '.' "
based on what I know I put the push method in the wrong place. I just copy the create method in the user which is working. I don't know why it is not working in order controller.
Note. I just started to learn json.
You have to update your routes like this as you are missing the totalAmount field and inside your schema you mentioned it as required fields.
router.post("/checkout", (req, res) => {
let data = {
userId : req.body.userId,
productId : req.body.productId,
totalAmount: req.body.totalAmount
}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})

How do I create a new board item in Monday.com w/ column values? Code is not working

I'm using the Monday.com API in a React bootstrapped app.
I can create a new board item successfully with an item name...
monday.api(
`mutation {
create_item (
board_id: ${myBoardId},
group_id: "new_group",
item_name: "new item creation",
)
{
id
}
}`
)
...but when I try to add additional column values I get a POST 500 error.
monday.api(
`mutation {
create_item (
board_id: ${myBoardId},
group_id: "new_group",
item_name: "new item creation",
column_values: {
person: 00000000,
}
)
{
id
}
}`
)
I've tried passing a string in for the column values...
let columnValues = JSON.stringify({
person: 00000000,
text0: "Requestor name",
text9: "Notes",
dropdown: [0],
})
monday.api(
`mutation {
create_item (
board_id:${myBoardId},
group_id: "new_group",
item_name: "test item",
column_values: ${columnValues}
)
{
id
}
}`
).then(res => {
if(res.data){
console.log('new item info: ', res.data)
};
});
...but no item is created, I get no errors and nothing logs.
Probably the problem is with your GraphQL query. To create an Item in Monday you need to provide the column_values. Unfortunately in Monday API documentation it's not clearly specified how it should be done. The answer how you need to provision column_values to create_item query can be found in Changing column values with JSON section of Monday API documentation
Please try the following code:
const board_id = "<board_id>"
const group_id = "<group_id>"
const person_id = "<person_id>"
const item_name = "<item name>"
let query = `mutation { create_item (board_id:${board_id},group_id: \"${group_id}\",item_name: \"${item_name}\",column_values: \"{\\\"person\\\":\\\"${person_id}\\\"}\"){id}}`
monday.api(query).then((res) => {
console.log(res);
})
Where,
<board_id> - your Board ID
<group_id> - your Group ID
<item_name> - the name of item you want to create
<person_id> - User ID
If you console.log query, you should see something like the following:
mutation { create_item (board_id:1293656973,group_id: "group_1",item_name: "New Item",column_values: "{\"person\":\"14153685\"}"){id}}
Please note that in query variable I am using String Interpolation. So the string should start and end with ` sign
You can also always dump your GraphQL queries and test them online using Monday API Try-It yourself tool
Here was the solution:
const variables = ({
boardId : 00000000,
groupId: "new_group",
itemName : "New Item",
columnValues: JSON.stringify({
people78: {
personsAndTeams: [
{
id: 00000000,
kind: "person"
}
]
},
text0: "Yosemite Sam",
dropdown: {
labels: [
"TAM"
]
},
})
});
const query = `mutation create_item ($boardId: Int!, $groupId: String!, $itemName: String!, $columnValues: JSON!) {
create_item (
board_id: $boardId,
group_id: $groupId,
item_name: $itemName,
column_values: $columnValues
)
{
id
}
}`;
monday.api(query, {variables}).then((res) => {
console.log('new item info: ', res);
});

Item count in Sharepoint list using spfx

I need the count of Status column in Sharepoint list. I have used React as the mode in spfx.
#autobind
private async _loadAsyncData(): Promise<Chart.ChartData> {
const items: any[] = await sp.web.lists.getByTitle("Sales").items.select("Title", "Salesamt", "Status").get();
let lblarr: string[] = [];
let dataarr: number[] = [];
items.forEach(element => {
lblarr.push(element.Title);
dataarr.push(element.Salesamt);
});
let chartdata: Chart.ChartData = {
labels: lblarr,
datasets: [{
label: 'My data',
data: dataarr
}]
};
return chartdata;
}
Can someone help me to get the count of items in the status column in the above code
Hi Nilanjan Mukherjee,
If your list is not very large, you can consider enumerating the whole list.
Another way is to use RenderListData() + CAML/Aggregations
Create a test list
Use below PnP code to get the count (note that the count is 2 while the row number is 3)
const caml: ICamlQuery = {
ViewXml: `<View><ViewFields><FieldRef Name="Title"/><FieldRef Name="johnjohn"/></ViewFields><Aggregations Value="On"><FieldRef Name="johnjohn" Type="Count"/></Aggregations></View>`
};
const r = await sp.web.lists.getByTitle('mm').renderListData(caml.ViewXml);
console.log(r);
Result:
Check below blog to get more details:
https://codeatwork.wordpress.com/2017/10/13/aggregation-using-caml-query/
BR

Mongoose: How to use data from a schema (product value) to populate a field in another schema () using a method?

Is it possible to use values within a schema that came from another Schema to fulfill the requirements of a new document?
I have two schemas; the first one is called Products and the second one is called Orders.
Products Schema has two fields:
name (String)
price (number).
models/products.js:
var mongoose = require('mongoose')
var productSchema = mongoose.Schema({
name: String,
price: {type: Number}
})
module.exports = mongoose.model('Product', productSchema)
Orders Schema has two fields too:
products_ids which are an array of ObjectId of products [ObjectId]
total_price which should be the sum of all the products prices.
models/order.js:
var mongoose = require('mongoose')
const Product = mongoose.model('Product')
var orderSchema = mongoose.Schema({
product_id: [{type: mongoose.Schema.Types.ObjectId, ref: 'Product'}],
total_price: getTotal(this.product_id)
})
function getTotal(arrId){
if (arrId.length === 0) {
return 0;
}
let totalPrice = 0
arrId.forEach((id) => {
let prod = new Product()
prod.findById(id, (product)=>{
totalPrice += product.price
})
})
return totalPrice;
}
module.exports = mongoose.model('Order', orderSchema)
this last field (total_price) is causing me troubles because I want to create a method which iterates through all the values in “this.products_ids.” array and automatically returns the sum of all the prices
the error that I am getting is the following:
“Schema hasn’t been registered for model “Product”.”
Is there a work around of this? Can I do what I think here or should I calculate the sum of the product’s price outside of my model?
You can use the .pre function. for example in your code:
var mongoose = require('mongoose')
const Product = mongoose.model('Product')
var orderSchema = mongoose.Schema({
product_id: [{type: mongoose.Schema.Types.ObjectId, ref: 'Product'}],
total_price: {type: Number, default:0}
})
orderSchema.pre('save', getTotal (next) {
let order = this;
if (arrId.length === 0) {
return 0;
}
let totalPrice = 0
arrId.forEach((id) => {
let prod = new Product()
prod.findById(id, (product)=>{
totalPrice += product.price
})
})
order.total_price= totalPrice;
});
module.exports = mongoose.model('Order', orderSchema)

how to make primary key / _id optional to input in mongoose

I want make primary key no need to input but primary key auto generate in mongodb.
so, i use {type : ObjectId,required:false}, but it wont work because I let the primary key empty. so is there another ways to make pprimary key optional to input? Thankyou
rest api model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId
var accessmenu = new Schema({
_id : {type : ObjectId,required: false},
acc_id : String,
name : String,
read : Boolean,
execute : Boolean
},{ collection: 'access_menu'});
var accessmenu = mongoose.model("accessmenu",accessmenu);
module.exports.accessmenu = accessmenu;
rest api
app.put("/access_menu/:id",function(req,res){
var AccessMenu = new accessmenu({
_id : req.body._id,
acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
});
AccessMenu.save(function(err){
if(err)
{
accessmenu.update({_id : req.params.id},{$set:{acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
}},function(err,users){
if(err)
{
data['error'] = 1;
data['Access_Menu'] = "update faill";
res.json(data);
}
else
{
data['error'] = 0;
data['Access_Menu'] = "update success";
res.json(data);
}
});
}
else
{
data['error'] = 0;
data['Access_Menu'] = "input success";
res.json(data);
}
});
});
script.js
if($scope.data_acc_lv.length > 0)
{
for(var i = 0;i<$scope.data_acc_lv.length;i++)
{
var input3 = {
"_id" : $scope.data_acc_lv[i]._id,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].name,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute
}
$http.put("http://localhost:22345/access_menu/" + $scope.data_acc_lv[i]._id,input3)
.success(function(res,err){
if(res.error == 0)
{
$scope.data_acc_lv.length = 0;
}
else
{
console.log(err);
}
});
}
}
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior.
If you don't want an _id added to your child schema at all, you may disable it using this option.
// disabled _id
var childSchema = new Schema({ name: String }, { _id: false });
var parentSchema = new Schema({ children: [childSchema] });
You can only use this option on sub-documents. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an _id.
http://mongoosejs.com/docs/guide.html

Categories

Resources