Elastic search delete operation - node.js

Am new to elastic search and struggling to delete an entry from my collection.
I need a query similar to this one
DELETE FROM message WHERE id='1323'" and created_user = "user#gmail.com".
Following are my elastic search query, when i execute this, its only deleting the particular id field, its not taking the second argument created_user. Please help me to solve this issue. Thanks
var created = "9ed8afe738aa63c28b66994cef1f83c6"
db.delete({
index: 'outboxpro',
type: 'message',
id: req.body.post_id,
created_user: created
}, function (error, resp) {
if (error) {
return next(error);
}
var data = {};
console.log('delete response',resp);
if (resp.hits.successful < 1) {
data = {status: false, message: 'NO POST FOUND TO DELETE', code: 400};
res.send(data);
} else {
return next({status: true, message: 'POST DELETED', data: error, code: 500});
}
});
//// EDIT
I have tried deleteByQuery, following are my code
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body:{
"query": {
"filtered": {
"query": {
"match": {
"_id": {
"query": "Kal4AXi5R9G-IMx4GIKYMw"
}
}
},
"filter": {
"and": [
{
"term": {
"created_user": created
}
}
]
}
}
}
}
}, function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});

You can delete documents matching your query, using delete by query in elasticsearch.. Refer
http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/api-reference-1-0.html#api-deletebyquery-1-0
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body: {
"query": {
"filtered": {
"query": {
"match": {
"_id": "Kal4AXi5R9G-IMx4GIKYMw"
}
},
"filter": {
"term": {
"created_user": "created"
}
}
}
}
},
function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});

The delete API will do exactly what you want, just in a slightly round-about way.
What you'll have to do first is search for the documents you want to delete, so construct a search query that find all documents with the id of '1323' and a created_user of 'user#gmail.com'. From the returned documents you'll be able to retreive the document ID which you then need to pass through to the delete API.
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete.html

Related

mongoose query multiple operations in one request

I'm trying to use the $set, $addToSet and $inc at the same time for my report of sales and
tbh I'm not even sure if I did the right approach since it's not working.
once I send the request, the console gives me the error 404 but when I check the req.body the data was correct. so I was wondering if the problem is my query on mongoose because this was the first time I use multiple operations on mongoose query
export const report_of_sales = async (req, res) => {
const { id } = req.params;
console.log(req.body);
try {
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'Invalid ID' });
let i;
for (i = 0; i < req.body.sales_report.length; i++) {
await OwnerModels.findByIdAndUpdate(id, {
$inc: {
total_clients: req.body.total_clients,
total_product_sold: req.body.sales_report[i].qty,
sales_revenue: req.body.sales_report[i].amount
},
$set: {
"months.$[s].month_digit": req.body.months[i].month_digit,
"months.$[s].targetsales": req.body.months[i].targetsales,
"months.$[s].sales": req.body.months[i].sales,
},
$addToSet: {
sales_report: {
$each: [{
identifier: req.body.sales_report[i].identifier,
product_name: req.body.sales_report[i].product_name,
generic_name: req.body.sales_report[i].generic_name,
description: req.body.sales_report[i].description,
qty: req.body.sales_report[i].qty,
amount: req.body.sales_report[i].amount,
profit: req.body.sales_report[i].profit
}]
}
}
}, {
arrayFilters: [
{
"s.month_digit": req.body.months[i].month_digit
}
],
returnDocument: 'after',
safe: true,
}, { new: true, upsert: true })
}
} catch (error) {
res.status(404).json(error);
}
}
Well, you are looking at the body, but you are actually using query parameter named id. This is probably undefined, which leads to ObjectId.isValid(id) returning false.
You should decide on whether to pass this data as a query param or in the request body and adjust your code accordingly.

sequelize Mysql data two between date all record show but some ... findall REST API ......simple problems

This my API Code .it work perfectly but missing my "startedDate":"2022-01-01", and
"endDate":"2022-01-31" … how I write the the function pls solved my problem and share your idea..
async getcurrentmonthorder2(req, res, next) {
try {
const {startedDate ,endDate} = req.body;
db.product.findAll({
attributes:[[sequelize.fn('sum',sequelize.col('profit_total')),'total']],
where : {"createdAt" : {[Op.between] : [new Date(startedDate).setHours(0,0,0,0) , new Date(endDate).setHours(23,59,59,999) ]}},
})
.then(list => {
res.status(200).json({ 'success': true, data: list });
})
.catch(function (err) {
next(err)
});
}
catch (err) {
res.status(500).json({ 'errors': "" + err });
}
}
#I have got output from postman..
{
"success": true,
"data": [
{
"total": "121",
}
]
}
#but I want to this output pls help share your idea
{
"success": true,
"data": [
{
"total": "121",
"startedDate":"2022-01-01",
"endDate":"2022-01-31"
}
]
}
my data
{id: 1, total: 20, profit_total: 15, createdAt: "2021-12-30T15:59:10.000Z",…}
Your problem comes from the attributes which you indicated in your query: You told SEQUELIZE to return only TOTAL. I suggest you this::
db.product.findAll({
attributes:[[sequelize.fn('sum',sequelize.col('profit_total')),'total'], 'startedDate', 'endDate'],
where : {
"createdAt" : {
[Op.between] : [new Date(startedDate).setHours(0,0,0,0), new Date(endDate).setHours(23,59,59,999) ]}
},
})

Firebase database collection returns empty array when trying to get all documents

I'm trying to get all documents from my database collection "posts" but I'm getting an empty array instead.
The strange thing is that I'm able to get all documents from another collection called "users" that has the same structure and using the exact same code.
I've spent days looking for an answer but I haven't been able to find the solution.
This is the request:
const db = admin.firestore();
exports.getAllPosts = (req, res) => {
db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let posts = [];
snapshot.forEach((doc) => {
posts.push({
id: doc.id,
body: doc.data().body,
author: doc.data().author,
createdAt: doc.data().timestamp,
voteScore: doc.data().voteScore
});
});
return res.json(posts);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And this is the response:
[]
This is what my current collection looks like:
Posts collection screenshot
This the response that I get when I return "snapshot":
{
"_query": {
"_firestore": {
"_settings": {
"projectId": "readable-bf7a6",
"firebaseVersion": "9.6.0",
"libName": "gccl",
"libVersion": "4.10.0 fire/9.6.0"
},
"_settingsFrozen": true,
"_serializer": {
"allowUndefined": false
},
"_projectId": "readable-bf7a6",
"registeredListenersCount": 0,
"bulkWritersCount": 0,
"_backoffSettings": {
"initialDelayMs": 100,
"maxDelayMs": 60000,
"backoffFactor": 1.3
},
"_clientPool": {
"concurrentOperationLimit": 100,
"maxIdleClients": 1,
"activeClients": {},
"failedClients": {},
"terminated": false,
"terminateDeferred": {
"promise": {}
}
}
},
"_queryOptions": {
"parentPath": {
"segments": []
},
"collectionId": "posts",
"converter": {},
"allDescendants": false,
"fieldFilters": [],
"fieldOrders": [
{
"field": {
"segments": [
"createdAt"
]
},
"direction": "DESCENDING"
}
],
"kindless": false
},
"_serializer": {
"allowUndefined": false
},
"_allowUndefined": false
},
"_readTime": {
"_seconds": 1622395245,
"_nanoseconds": 513743000
},
"_size": 0,
"_materializedDocs": null,
"_materializedChanges": null
}
Notice how the request for the collection "users" works successfully:
const db = admin.firestore();
exports.getAllUsers = (req, res) => {
db.collection('users')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let users = [];
snapshot.forEach((doc) => {
let users = [];
snapshot.forEach((doc) => {
users.push({
id: doc.data().userId,
email: doc.data().email,
handle: doc.data().handle
});
});
return res.json(users);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And the response:
[
{
"id": "EPoHBxhQFUXbcL3TCVx1LdUG2nO2",
"email": "ruben#gmail.com"
},
{
"id": "RqEa3dEq8TSDcZYeolXafju67rB2",
"email": "user10#gmail.com"
},
{
"id": "dxveb4n2iMQej5Q14uprsKRxFp23",
"email": "user4#gmail.com",
"handle": "user4"
},
{
"id": "YQPzBPcsqlVZk9iJEuZTHKUNuVG2",
"email": "user2#gmail.com",
"handle": "user2"
},
{
"id": "CZ05BJxi3TUOpIrmBaz539OWlbC3",
"email": "user#gmail.com",
"handle": "user"
},
{
"id": "t0t83BVwt4gVgJkDv7HL1r1MaKr1",
"email": "userJose2#gmail.com",
"handle": "Jose"
}
]
This is what the users collection looks like in Firebase:
Users collection screenshot
Why is one collection failing when the other works fine and I'm using the same code? What am I missing here?
Thanks in advance and I hope I've made it as clear as possible. Please let me know if you need me to provide anything else.
Very simple my friend, your posts documents can't be ordered like this:
.orderBy('createdAt', 'desc')
Because the post documents does not have the createdAt property, but they have a timestamp property, you should use that property to order your posts like this:
.orderBy('timestamp', 'desc')
I hope that helps 👍
I am not answering directly to #Ruben Garcia Bri, but for future firebase developers who may run into the problem of getting empty documents, I also ran into the same problem, but I solved it by adding a field to the particular document I am trying to retrieve.
Sometimes the cause is because the documents you are trying to get have no field in them.
I mean that a document must have a field before the server can recognize it as an existing document.
So if you run into this problem, consider adding a field to that document before you can successfully retrieve it.

Mongoose - replace all array elements

I want to replace all array's elements in 'prices' filed as below:
{
"name": "My customer name"
"taxCode":123456
"prices":
[
{
"name": "Chocolate",
"unitPrice": 10
},
{
"name": "Cookie",
"unitPrice": 9
}
]
}
The JSON that uses to change 'prices' is:
{
"prices":
[
{
"name": "Chocolate1",
"unitPrice": 10
},
{
"name": "Candy",
"unitPrice": 5
}
]
}
And here is my code to replace the 'prices' array
router.route('/:obj/:id')
.put((req, res) => {
const PObj = require('../models/customer');
PObj.findById(req.params.id, (err, doc) => {
if (err) {
console.log('Lookup error: ' + err);
res.status(500).send('Error');
} else if (doc) {
doc.update({$set: req.body}, (err, task) => {
res.status(200).json(task);
}); } else {
res.status(404).send('Something is wrong');
}
});
});
After code executed is done but without any changes in Mongo DB. Please help me to correct my code. Thank!
If your req.body prints that prices array then it has to be req.body.prices, also rather than fetching the document & updating it - Which is a two- way process, You can try this :
router.route("/:obj/:id").put((req, res) => {
const PObj = require("../models/customer");
PObj.findByIdAndUpdate(
req.params.id, /** this 'req.params.id' has to be `_id` value of doc in string format */
/** internally mongoose will send this as { $set: { prices: req.body.prices }} which will replace `prices` array will new array,
* Just in case if you wanted to push new values, have to manually do { $push: { prices: req.body.prices }} each object */
{ prices: req.body.prices },
{ new: true }, /** returns updated doc, this option is not needed if you don't need doc - by default it returns old doc */
(err, doc) => {
if (err) {
console.log("Lookup error: " + err);
res.status(500).send("Error");
} else if (doc) {
res.status(200).json(task);
} else { /** `doc` value will be null if no doc is not found for given id */
res.status(404).send("Something is wrong");
}
}
);
});
Ref : .findByIdAndUpdate()

Unable to $push and $set the data at a time in mongodb using express js

I have a scenario where I need to replace the data in one array and also push the data in another array in one query itself.
Here I'm using express js framework and mongoose for queries.
Here is the query which I wrote:
exports.candidateRating = function(req, res) {
console.log(req.query);
Profiles.update({
"name": req.query.name
}, {
$set: {
"ratings": req.body.ratings,
}
}, {
$push: {
"RoundWiseRatings": req.body.RoundWiseRatings
}
}, function(error, profiles) {
if (error) {
}
return res.status(200).json(fnStruncturedData(profiless));
});};
Here I'm able to set the data but unable to push data.
I don't understand where I'm wrong.
Any help would be highly appreciated.
You have wrong syntax, you add $push as another parameter for update function, but you do want to add it as another part of the second parameter.
This is syntax of update
Model.update(conditions, update, options, callback);
I think this should work :
exports.candidateRating = function(req, res) {
console.log(req.query);
Profiles.update({
"name": req.query.name
}, {
$set: {
"ratings": req.body.ratings,
},
$push: {
"RoundWiseRatings": req.body.RoundWiseRatings
}
}, function(error, profiles) {
if (error) {
}
return res.status(200).json(fnStruncturedData(profiless));
});};
Also you probably want to update multiple documents, which means you should use multi parameter in options
exports.candidateRating = function(req, res) {
console.log(req.query);
Profiles.update({
"name": req.query.name
}, {
$set: {
"ratings": req.body.ratings,
},
$push: {
"RoundWiseRatings": req.body.RoundWiseRatings
}
}, {
multi: true
}, function(error, profiles) {
if (error) {
}
return res.status(200).json(fnStruncturedData(profiless));
});};

Resources