Update data in MongoDB with Moongoose and MEAN Stack - angularjs

I have a mongoose data like this:
{
"_id" : ObjectId("58e394cacaa6512ed00e8d83"),
"RoleName" : "Manager",
"UIList" : [
{
"Edit" : false,
"View" : false,
"UiName" : "ElevatorMapping"
},
{
"Edit" : false,
"View" : false,
"UiName" : "ElevatorAssumptions"
},
{
"Edit" : false,
"View" : false,
"UiName" : "ManageUnits"
},
{
"Edit" : false,
"View" : false,
"UiName" : "ManageBuildings"
}
],
"__v" : 0,
"Description" : "fd",
"IsActive" : true
}
Now I want to update UILIST inside UIname:"ElevatorMapping"&"Elevator Assumptions" View and Edit as True. How to write query for this? I have tried something like below.
Here is my Controller page.
$http.put('/ViewEditupdate/' + id +'/' + uiname + '/' + view + '/' + edit).then(function (response) {
refresh();
})
Here id value is taken correctly but the Edit view UI names are not taken. Edit , view name are taken as undefined.
My server.js code
app.put('/ViewEditupdate/:id/:uiname/:view/:edit', RoleEntrypath.RoleViewEditupdate);
my Schema code
newRole.update({ "UIList.UiName": "ManageRole" }, { "$push": { "UIList.$.View": "true", "UIList.$.Edit": "true" } },
function (err, doc) {
res.json(doc);
}
);
Can anyone give the solution?

you should use $set instead of $push to change the value of view from false to true.
Try this:
newRole.update({
"UIList.UiName": "ManageRole"
},{
$set: { "UIList.$.View": "true", "UIList.$.Edit": "true" }
},function (err, doc) {
res.json(doc);
});

i already updated by using this query.
newRole.update
(
{
_id: id,
"UIList.UiName": "ManageRole"
},
{
$set: {
"UIList.$.View": "true",
"UIList.$.Edit": "true"
}
},
function (err, doc) {
res.json(doc);
}
);

Related

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 documents nested multiple levels in an array

I have this JSON structure in MongoDb and want to update changing a specific value of a particular item in a nested array. I would like to change the key targetAreaId from USER_MESSAGE to VISUAL_MESSAGE.
{
"_id" : "5cde9f482f2d5b924f492da2",
"scenario" : "SCENARIOX",
"mediaType" : "VISUAL",
"opCon" : "NORMAL",
"stepConfigs" : [
{
"stepType" : "STEPX",
"enabled" : true,
"configs" : [
{
"contentTemplateId" : "5cde9f472f2d5b924f492973",
"scope" : "STANDARD",
"key" : "CONTENT"
},
{
"priorityId" : "5cde9f472f2d5b924f49224f",
"scope" : "STANDARD",
"key" : "PRIORITY"
},
{
"targetAreaId" : "USER_MESSAGE",
"scope" : "STANDARD",
"key" : "TARGET_AREA"
}
],
"description" : "XPTO"
}
],
"scope" : "STANDARD" }
How can I do it in the same time?
EDIT
I am trying this way:
var cursor = db.getCollection('CollectionX').find({
"scenario": "SCENARIOX",
"stepConfigs.stepType": "STEPX",
"stepConfigs.configs.key": "TARGET_AREA"
});
if (cursor.hasNext()) {
var doc = cursor.next();
doc.stepConfigs.find(function(v,i) {
if (v.stepType == "STEPX") {
doc.stepConfigs[i].configs.find(function(w,j) {
if (w.key == "TARGET_AREA") {
var result = db.getCollection('CollectionX').update(
{ "_id" : doc._id },
{ "$set" : { doc.stepConfigs[i].configs[j].targetAreaId: "VISUAL_MESSAGE" }}
);
}
});
};
});
} else {
print("Step does not exist");
}
But the error below is occurring:
Error: Line 15: Unexpected token .
I don't think that's possible.
You can update the specific element you want using this query:
db.test_array.updateOne({}, {
$set: {
"stepConfigs.$[firstArray].configs.$[secondArray].targetAreaId": "VISUAL_MESSAGE"
}
}, {
arrayFilters: [{
"firstArray.stepType": "STEPX"
}, {
"secondArray.targetAreaId": "USER_MESSAGE"
}]
})
But pushing in the same array at the same time does render this (this was for the original model, but it's still the same problem, you can't $set and $push in the same array this way):
> db.test_array.updateOne({"step.type":"B"},{$push:{"step.$.configs":{"className":"something"}}, $set:{"step.$.configs.$[secondArray].targetAreaId":"TA-1"}},{arrayFilters:[{"secondArray.targetAreaId":"TA-2"}]})
2019-09-06T13:53:44.783+0200 E QUERY [js] WriteError: Updating the path 'step.$.configs.$[secondArray].targetAreaId' would create a conflict at 'step.$.configs' :

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."

Delete Array item from mongoDB collection

I am trying to do following, if anyone could help would be great help
I want to delete an item from the items array
{
"_id" : ObjectId("56e8c56a71cfa3fbe528c91b"),
"shipping" : 6.7800000000000002,
"subTotal" : 201,
"totalCost" : 207.7800000000000011,
"order_status" : "queued",
"ordered_by" : "John Sims",
"ordered_by_id" : "56e8c50a71cfa3fbe5288a48",
"created_at" : ISODate("2016-03-16T02:31:06.723Z"),
"items" : [
{
"created_at" : "2008-12-17T11:01:23.460Z",
"quantity" : 1,
"country" : "Australia",
"state" : "NSW",
"suburb" : "Sydney",
"location" : "Sydney,NSW,Australia",
"longitude" : "151.1228434",
"latitude" : "-33.7904955",
"genre" : "Rock",
"cost" : "67",
"product_status" : "pending",
"product_by" : "Paul Dirac",
"item" : "CD",
"cart_id" : "56e8c56271cfa3fbe528c918"
},
{
"created_at" : "2008-12-17T11:01:23.460Z",
"quantity" : 1,
"country" : "Australia",
"state" : "QLD",
"suburb" : "Brisbane",
"location" : "Brisbane,NSW,Australia",
"longitude" : "151.1228434",
"latitude" : "-33.7904955",
"genre" : "",
"cost" : "67",
"product_status" : "pending",
"product_by" : "Paul Dirac",
"item" : "DVD",
"cart_id" : "56e8c56571cfa3fbe528c919"
}
]
}
Based on conditions like below
// Updates an existing order in the DB.
exports.updateArray = function(req, res) {
Order.findById(req.params.id, function (err, order) {
if (err) { return handleError(res, err); }
if(!order) { return res.send(404); }
order.update(
// query
{
},
// update
{
$pull:{
items:{
"item" : "CD"
}
}
}
);
order.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, order);
});
});
};
Now update code runs and remove item from items when code being executed from shell with following
db.getCollection('orders').update(
// query
{
},
// update
{$pull:{
items:{
item:'CD'
}
}
},
// options
{
"multi" : false, // update only one document
"upsert" : false // insert a new document, if no existing document match the query
}
);
But when run over put or delete request, this doesn't remove the item from the items array of the specific document. If anyone could help me figure out the code needs to change to make it happen over HTTP request would be great.
Thanks
db.collection.findOneAndUpdate({_id:'56e8c56a71cfa3fbe528c91b'},
{$pull:{"items.item":"cd"}},{new:true},function(err,object{
});
You can use $pull in mongodb query .
this query i used in mongoose in ndoe js and it could be work for me..
Working Solution is now this
exports.updateArray = function(req, res) {
Order.update(
// query
{
_id:req.params.id
},
// update
{
$pull:{
items:{
item:itemdata
}
}
},function(err){
return res.send(204);
}
);
};

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