DeleteOne by _id Mongodb - reactjs

This is my first stack overflow question, and I'm excited to hear your thoughts.
> db.travelers.find().pretty()
{
"_id" : ObjectId("615e3ddece93c870aca4e465"),
"assembly" : [
{
"_id" : ObjectId("615e3ddece93c870aca4e466"),
"SN" : 24,
"Model" : "J240",
"Job" : 1234,
"Revision" : "A",
"Version" : 1
}
],
"assyHistory" : [ ],
"subAssemblies" : [
{
"_id" : ObjectId("615e3deace93c870aca4e467"),
"SN" : 19,
"Model" : "P500"
}
I am trying to delete the nested data in "subAssemblies" by its id. My current route:
router.delete("/subassembly/:id", deleteOneSubassembly);
my current controller:
deleteOneSubassembly: async (req, res) => {
try {
const removeOne = await Traveler.deleteOne({
_id: req.params.id
});
console.log(removeOne);
res.json(removeOne);
} catch (err) {
res.send({ error: err });
}
}
And all I keep getting back is:
"n": 0,
"nModified": 0,
"ok": 1
Wondering where I might be going wrong?

use update and $pull the item
const removeOne = await Traveler.updateOne(
{
"subAssemblies._id": req.params.id
},
{
"$pull": { subAssemblies: { _id: req.params.id }
}
});
aggregate
db.collection.update({
"subAssemblies._id": ObjectId("615e3deace93c870aca4e467")
},
{
$pull: {
subAssemblies: {
_id: ObjectId("615e3deace93c870aca4e467")
}
}
})
mongoplayground

Related

How can I find subdocument using Mongoose?

I have defined a model like this.
const ShotcountSchema = new Schema({
shotCountId : {
type : ObjectId,
required : true,
ref : 'member-info'
},
userId : {
type : String,
required : true,
unique : true
},
shot : [{
shotId : {
type : String,
required : true,
unique : true
},
clubType : {
type : String,
required : true
}
createdAt : {
type : Date,
default : Date.now
}
}]
});
If you perform a query to find subdocuments based on clubType as follows, only the results of the entire document are output.
For example, if I write the following code and check the result, I get the full result.
const shotCount = await ShotcountSchema.aggregate([
{
$match : { shotCountId : user[0]._id }
},
{
$match : { 'shot.clubType' : 'driver' }
}
]);
console.log(shotCount[0]); // Full result output
I would like to filter the subdocuments via clubType or createdAt to explore. So, I want these results to be printed.
{
_id: new ObjectId("61d67f0a74ec8620f34c57ed"),
shot: [
{
shotId: 'undefinedMKSf*Tf#!qHxWpz1hPzUBTz%',
clubType: 'driver',
shotCount: 20,
_id: new ObjectId("61d67f0a74ec8620f34c57ef"),
createdAt: 2022-01-06T05:32:58.391Z
}
]
}
How should I write the code?
db.collection.aggregate([
{
"$match": {
_id: ObjectId("61d67f0a74ec8620f34c57ed"),
"shot.clubType": "driver",
shot: {
$elemMatch: {
$and: [
{
"createdAt": {
$gte: ISODate("2022-01-07T05:32:58.391Z")
}
},
{
"createdAt": {
$lte: ISODate("2022-01-09T05:32:58.391Z")
}
}
]
}
}
}
},
{
"$set": {
shot: {
"$filter": {
"input": "$shot",
"as": "s",
"cond": {
$and: [
{
"$eq": [
"$$s.clubType",
"driver"
]
},
{
"$gte": [
"$$s.createdAt",
ISODate("2022-01-07T05:32:58.391Z")
]
},
{
"$lte": [
"$$s.createdAt",
ISODate("2022-01-09T05:32:58.391Z")
]
}
]
}
}
}
}
}
])
mongoplayground

ARRAY FILTERS in mongooDB

I have the following schema
{
"_id" : ObjectId("5ec0471dfec11a07d80c9d07"),
"name" : "jasper",
"post" : [
{
"_id" : ObjectId("5ec0473ffec11a07d80c9d08"),
"content" : "It,s all about........",
"title" : "THE NEEDY"
},
{
"_id" : ObjectId("5ec0475afec11a07d80c9d09"),
"content" : "I know..........",
"title" : "The world"
}
],
"__v" : 2
}
I want to update the content part in a particular post. I am using mongoose.
I tried the below query.Though it isn't showing any error it isn't updating in the data in the database.
var id="5ec0471dfec11a07d80c9d07";
var subid="5ec0473ffec11a07d80c9d08";
data.updateOne(
{'_id.post._id':subid},
{
$set:{
"$[post].post.$[rely].content":'ohkkk'
}
},
{arrayFilters:[{"post._id":id},{"rely._id":subid}],new:true}
);
Can you please help me find the error?
If you wanted to use arrayFilters, please try the code below:
data.updateOne({_id: id},
{
"$set": {[`post.$[inner].content`]: 'ohkkk'}
},
{
"arrayFilters": [{ "inner._id": subid }],
new: true
},
function(err, post) {
if (!err) {
res.send(post)
}
})
Alternatively, since it is 1 level nested array you could do:
data.updateOne({ _id: id, "post._id": subid }, { $set: { "post.$.content": 'ohkkk' }, { new: true } })
Hope it helps.

Update an element of an Array in a Document in MongoDB with Mongoose

I have a MongoDB database whith a collection with this structure:
{
"_id" : ObjectId("5b670eefe94672265ca59428"),
"duration" : {
"start" : ISODate("2018-09-01T00:00:00.000Z"),
"end" : ISODate("2018-09-01T00:00:00.000Z")
},
"title" : "Example title.",
"description" : "<p>Hi example!</p>",
"slug" : "title",
"insertDate" : ISODate("2018-08-05T14:51:27.194Z"),
"webData" : [
{
"_id" : ObjectId("5bb1f082931c536950ade361"),
"webCode" : "be_mx",
"categories" : [
{
"_id" : ObjectId("3sdf43f34543et35tret435"),
"name" : "Category 1",
"webCode" : "be_mx",
"slug" : "category-1"
},{
"_id" : ObjectId("3sdf43f34543et35tretert"),
"name" : "Category 2",
"webCode" : "be_mx",
"slug" : "category-2"
}
]
}
],
"__v" : 6,
"lastEditionDate" : ISODate("2018-10-01T10:01:38.889Z")
}
I want to update all documents from this collection that has a categorie with a _id = "3sdf43f34543et35tret435" (in this example the "Category 1"), and I want to update this element category setting, for example, the slug to "category-3".
I tried to do that with this code:
Collection.update({
"webData.categories": {
$elemMatch: {
_id: ObjectId("3sdf43f34543et35tret435")
}
}
}, {
$set: {
webData: {
"categories.$.slug": "category-3"
}
}
}, {
multi: true
}, (err, res) => {
if (err) { console.log(err); }
console.log(res);
});
When I execute that, all the documents that have this category are edited but it's wrong because all the related categories are deleted.
Can you help me with this operation?
Thank you!
EDITED:
When I execute in my DB this query:
db.getCollection("scholarships").update({},
{ '$set': { 'webData.[].categories.$[category].slug': "nana" } },
{ multi: true, arrayFilters: [{ 'category._id': ObjectId("5b719d821f3f1131ec4524f6") }] })
Using in this time an arrayFilter, I receive this error:
The path 'webData.[].categories' must exist in the document in order to apply array updates."

Push data in nested arrays nodeJs, MongoDB

I Have Document Like,
{
"_id" : ObjectId("5ab4cc12c773133bae3d8dc9"),
"__v" : 19.0,
"geoGraphicalFilter" : {
"aCountries" : [
{
"country" : "Spain",
"_id" : ObjectId("5ad49ab21210c42aa6ccba23"),
"cities" : [ ]
},
{
"country" : "India",
"_id" : ObjectId("5ad49ab21210c42aa6ccba24"),
"cities" : [ ]
}
]
}
}
Model
const HuntingWindow = new Schema({
geoGraphicalFilter: {
aCountries: [
{
country: String,
cities: { type: Array }
}
]
},
});
Snippet
const addCityFilter = (req, res) => {
if (req.body.aCities === "") {
res.status(409).jsonp({ message: adminMessages.err_fill_val_properly });
return false;
} else {
var Cities = req.body.aCities.split(",");
huntingModel.update({ _id: req.body.id,"data.geoGraphicalFilter.aCountries":req.body.sName },
{$push:{"geoGraphicalFilter.0.aCountries.$.cities":Cities}},
(error, data) => {
// Cities.forEach(element => {
// data.geoGraphicalFilter.aCountries.find(req.body.sName)
// });
data.save((error, success) => {
res.status(200).jsonp({
message: adminMessages.succ_countryFilter_added
});
});
});
}
};
Now I want to first Find Document by root id and then I want to match the country name and insert the cities in the Array. I am new to MongoDB and nodejs how can i do this ? While i am trying to with update query but i thing i am doing it on wrong way plese help me with it.
Try following code:
huntingModel.update(
{ _id: ObjectId("5ab4cc12c773133bae3d8dc9"), "geoGraphicalFilter.aCountries.country": "Spain" },
{ $addToSet: { "geoGraphicalFilter.aCountries.$.cities": { $each: [ "city1", "city2" ] } } }
)
You should specify two filtering conditions: one for entire document and one to match array element. Then you can use $ operator to update first matching document in that array. To push multiple values you can use $each operator. To ensure that there will be no duplicates you should use $addToSet

MEAN-Stack MongoDB Sub Array Delete - Works in IDE, not in API

I have a [user] document stored that contains a nested sub-array [profiles],[favorites]. I am simply trying to delete($pull) a favorites from a given profile based on the favorites name.
{
"_id" : ObjectId("558d53eebdd9804820090fa1"),
"name" : "Frank",
"email" : "Frank#FrankTheTank.com",
"profiles" : [
{
"avatar" : "div-male",
"age" : "35",
"gender" : "Male",
"profilename" : "Oly Lifter",
"_id" : ObjectId("558d5404bdd9804820090fa2"),
"favorites" : [
{
"name" : "Power Clean"
},
{
"name" : "Hang Clean"
},
{
"name" : "Clean and Jerk"
}
],
"createdAt" : ISODate("2015-06-26T13:30:44.661Z")
}
],
"createdAt" : ISODate("2015-06-26T13:30:22.884Z"),
"role" : "user",
"__v" : 0
}
Using a MongoDB IDE robomongo, I'm able to successfully remove a favorite item from a known User and Profile ID using this
db.users.update($find: {
'profiles': {
'profiles._id': ObjectId("558d5404bdd9804820090fa2")
},
{
$pull: {
'profiles.$.favorites': {
'name': 'Hang Clean'
}
}
})
However, when I call from my server API using the following syntax, I receive an error, note req.body._id = "558d5404bdd9804820090fa2" and req.body.favorites.name = "Hang Clean"
User.findByIdAndUpdate(_user._id, {
'profiles._id': req.body._id
}, {
$pull: {
'profiles.$.favorites': {
'name': req.body.favorites.name
}
}
}, {
safe: true,
upsert: true
},
function(err, model) {
if (err) {
console.log(err);
return res.status(500).send('Error Deleting Profile');
}
return res.status(200).send('Profile Deleted!');
});
Try updating using the findOneAndUpdate() method since you are supplying the findByIdAndUpdate() method with the wrong parameters: the second argument { 'profiles._id': req.body._id } should be part of the first query object hence you need to use the findOneAndUpdate() method as follows, making sure you convert the string ids into ObjectId's:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(_user._id),
profileId = mongoose.Types.ObjectId(req.body._id),
query = {
"_id": id,
"profiles._id": profileId
},
update = {
"$pull": {
"profiles.$.favorites": { "name": req.body.favorites.name }
}
},
options = { "multi": true, "upsert": true };
User.findOneAndUpdate(query, update, options, function(err, model) {
if(err){
console.log(err);
return res.status(500).send('Error Deleting Profile');
}
return res.status(200).send('Profile Deleted!');
});

Resources