How to remove empty fields on Update - node.js

When I remove an array element from a document field, I would like to remove that field, if zero length, or empty object. I do not want fields with empty arrays or empty objects saved on db.
I use this snippet for update document:
await documentInstance.findByIdAndDelete(req.params.id,async(error,doc)=>{
await empInstance.findByIdAndUpdate(employId,{
$pull:{
documents:req.params.id
}
},{omitUndefined:true});
});
When I remove the only item from array, I get an empty array.
Thanks.

Related

Update specific field in an array of object in a MongoDb Document

I have a document with that format :
{
"field1":"string",
"field2":123,
"field3":
[
{
"subField1":"string",
"subField2": object,
// other fields after
},
{
"subField1":"string",
"subField2": object,
// other fields after
},
// other fields after
]
// other fields after
}
I want to update at once the field3.$.subField2 field only, with a different value in each of the elements of the array composing field3.
Does anyone knows how to properly do it ?
One reason I want to do this is I have several asynchronous operations that are meant to update differents fields of the array field, and I have concurrency issues...
I tried with findOneAndUpdate(query, $set{"field3.$.subField2": arrayOfValues}) but it does not works, it seems I can only pass one single value that would be set to each element of the array (all the same).
arrayOfValues would be of course an array with only the values I want with the matching indexes and same size of the document's array.

Get multiple documents from collection using nodejs and mongodb

Hi I have two mongodb collections. The first one returns json data (array) and with the output of this, I want to return documents that match.
When I run Console.log (req.bidder.myBids) I get the following output:
[{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3010},{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3020},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1040},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1050},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1060},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1070},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1090},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1100}]
The productId has duplicates, I want to remove duplicates and then call a routine that finds all the products that match and output as json.
So far I have this code that only outputs one document, but cant figure out how to add the array of productId's and then fetch all corresponding products.
var agencyId = req.body.agencyId;
var productId = req.body.productId;
if (!validate.STRING(agencyId)) {
res.apiError(messages.server.invalid_request);
} else {
dbProduct.find({productId:{$in:['3798b537-9c7b-4395-9e41-fd0ba39aa984','4c4bd71c-6664-4d56-b5d3-6428fe1bed19']}
}).then(dbRes => {
console.log(dbRes);
Updated code and works with hard-wired productId and updated above code. Looking at how to get the array data and transpose replacing the hard-wired productId's
The $in operator is what you want. See the docs here: https://docs.mongodb.com/manual/reference/operator/query/in/

Get all documents whose property equals one of the elements in an array

I have a Post model that has a publisher property defined in its schema (I'm using Mongoose). The publisher property is a string that refers to a publisher's name.
I also have an array called sourceNames that holds all the different publisher names. I want to query my database for ALL the posts whose publisher matches any one of the array elements in sourceName. My current query looks like this:
const query = postModel
.find({ publisher: { $all: sourceNames } })
.limit(limit)
.skip(startIndex);
My query isn't returning anything when I exec it. Does anyone know if what I'm trying to do is possible in a single query (Rather than loop over sourceNames and make a query for each individual element?
Short
Just replace $all with $in
Expl
$all is trying to match an array with all elements in your array.
$in instead, tries to match a string or array with one in the array.

Deleting a field with $unset operation it just converting it to a null value

I'm trying to delete some fields on my mongodb database but instead the fields are just getting mutated to a null value and that's an issue because when fetching data im using loops and they get broken passing true null value ... for deleting data i'm using the following :
User.updateOne({_id : user._id } ,{ $unset :{ "days.0.tasks.0" = "" })
what i'm getting :
Is there a way to delete entirely the objects inside the tasks array?
$unset is not working as you'd expect it because you are using it on an element inside an array. Removing the element at position 0 means shifting all other elements in the array. To prevent messing with those other elements, $unset is setting the element at position 0 to null.
MongoDB docs
I suggest using the $pull operator to delete specific elements from an array or use $pop for the first / last items .
OR :
you can get the user tasks array and splice it then push it back using $set operator.

how to validate if an array is empty using validator

I need to check if the users have filled in array values or they are empty .
I went through the validator docs
but I don't see any function which works on array .
isEmpty(str) check if the string has a length of zero.
validator validates and sanitizes strings only. so none of the methods in there will help you achieve what you want. just use Array.length property.
If by empty array, you mean: []
This will do:
if(!array.length)
console.log(`I'm not empty`);
If you mean an array with empty values, such as: [null, '']
You can use: .some to check if at least one item is empty, or .every to check that every item is empty.
const array = [null, ''];
!array.some(Boolean); // True if at least one is falsy
!array.every(Boolean); // True if every item is falsy
If you want some custom validation, you can pass your custom function too.
function empty(item) {
// What ever you consider by empty, check it here
// return true if it is empty
if(typeof item === 'string')
return !item.trim();
return !item;
}
array.some(empty); // true if at least one is empty
array.every(empty); // true if all of them are empty

Resources