use bulkDestroy in Sequelize - sql-delete

I'd like to know how to delete all values in an array, my array contains the ids like: [1,2,3,4], I've tried:
models.products
.destroy({where: {req.body.ids}})
.then(function(data){ res.json(data) })
But I got data undefined, and nothing is deleted...

You've missed the id from your criteria.
Model.destroy({ where: { id: [1,2,3,4] }})

Just to add to +Adam's response:
for arrays you'll need to add an $in: clause.
Models.products
.destroy({where: {$in: req.body.ids}})
...

Related

Mongoose find query - specific items or empty array

I'm trying to build a filter where it should be possible to query all items selected in an array, but also to show documents where the property has not been set.
returning all specific from an array works fine with below
searchCriteria.filter1 = {
$in: array.category,
};
searchCriteria.filter2 = {
$in: array.carbrand,
};
//Then the data if fetched
const fetchedData = await Activity.find(searchCriteria)
.sort({ date: -1 })
.limit(limit)
.skip(startIndex)
.exec();
However, sometimes users have not added a category, and it's just a empty array. My goal is to get all of these empty arrays as well as the specific arrays.
so something like:
searchCriteria.filter2 = {
$in: array.carbrand OR is []
};
Any suggestions?
One way you could approach this is indeed to use the $or operator. But since $in is logically an OR for a single value, you should be able to just append [] to the list being used for comparison by the $in operator.
The approach is demonstrated in this playground example.
I believe you could adjust the code in a manner similar to this:
searchCriteria.filter2 = {
$in: [...array.carbrand, []]
};

Push values in Mongo Nested Array

enter image description here
Let's say that we have many documents like this in the photo
I have the above schema. I want to find the document based on _id first and then push an array of values to providedServices which belongs to the _id which is inside barbers array
A little help. Can't seem to find this out!
You need to find the related arrays firstly. For this, you can use $elemMatch or write it as 'barbers._id' : {$elemMatch: parameter}' .
Here we tried to find document with filtering it's own id and barbers id. You can change the filter as you wished. It can be only search on barbers id.
Need to write your DocumentName and your parameters instead of idValue, barbersId, serviceModel.
const result = await DocumentName.findOneAndUpdate(
{
$and:
[
{_id: mongoose.Types.ObjectId(idValue)},
{'barbers': {$elemMatch: {_id: mongoose.Types.ObjectId(barbersId)}}}
]
},
{ $push: { 'barbers.$.providedServices': serviceModel } },
{ new: true })
At first, we found the related barbers array inside of all documents. Then we pushed the model inside of providedServices array into this barbers array.

Mongoose findOneAndUpdate an array within an array within a document

I'm trying to update an array that sits inside another array in a document. The schema is like this:
const projectSchema = new mongoose.Schema({
stakeholders: [{
stakeholderTitle: {
type: String,
},
...
subgroup: [{
subgroupTitle: {
type: String
},
subgroupPercent: {
type: Number,
}
}]
}],
and I'm trying to update the 'subgroup' array. I have got the query to work on its parent (the stakeholder array) with the positional $ operator, using the answer to this question I asked previously. So my query looks like this.....
await db.findOneAndUpdate({ find by the id }, { "stakeholders.$.stakeholderTitle": req.body.stakeholderTitle, ... "stakeholders.$.subgroup": req.body.subgroup })
However, this query doesn't work for the 'stakeholders subgroup' array, and makes it null. Looking through the mongo docs for the positional operator it states that 'The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value', which I guess might be my problem.
So how can I do this with a findOneAndUpdate query?
From what I see is you have to specify the object you want to update inside the subgroup array. Try this - (i.e I'm updating the subgroupTitle of the subgroup array);
await db.findOneAndUpdate(
{
_id: userId,
"stakeholders.stakeholderTitle": req.body.stakeholderTitle,
"stakeholders.stakeholderTitle.subgroup.subgroupTitle": req.body.subgroupTitle
},
{$set: {
"stakeholders.stakeholderTitle.subgroup.$.subgroupPercent": somePercentValue,
}
},
);
Also note, it's only the array that you find that you can update. It might not be exactly what you want, but its a step closer

How to write MongoDB query statement for a specific requirement?

Here is the MongoDB document format:
{
'_id':...,
'user_id':...,
'user_info':...,
...
}
The user_info's value is a number or a string, I'd like to combine all the user_info's value into an array as the key 'user_info' 's value in the query result, like here:
{ 'user_id': ..., 'user_info': [ ..., ...] }
How to write the query statement to query data like this?
You need to use $in
The $in operator selects the documents where the value of a field equals any value in the specified array.
db.users.find({'user_info': {$in: [1, "a"]}})
Here you can read about it $in

How do you limit an array subelement in Mongo?

Let's say I have the following data model in Mongo:
{
_id: ...,
name: "...",
obj: {...},
list: [ ... ],
}
Now let's say, my list array is very long, and I don't want to grab the whole document every time. So I want to get obj and name, but only grab the last 5 elements in list. How do you do this with with Mongo? I'm using pymongo.
I think you are looking for the $slice operator. Docs are here.
The syntax you are looking for is something like this:
db.coll.find({}, {obj:1, name: 1, list:{$slice: -5}}); // last 5
Note that this will also return the _id field by default. If you do not want the _id add _id:0 in front of obj:1. This is the JS syntax, but the python syntax will be very close.
use $slice operator to limit array elements
GeoLocation.find({},{name: 1, geolocation:{$slice: -5}})
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
where geolocation is array of data, from that we get last 5 record.