How to push object without filed name in mongodb with nodejs - arrays

This is my Schema design
mongoose.Schema({
traffic_countries:String,
company_details:String,
campaigns:[{
_campaignid : mongoose.Schema.Types.ObjectId,
}],
impressions:[{
country:String,
_campaignid :mongoose.Schema.Types.ObjectId
}],
payments:[],
budget:String })
What i want to do
I want to push the object below in the payments array the code that i am using for this purpose is given below the object
{
"id" : "PAY-52L98986JB4797714LN73QTY",
"intent" : "sale",
"state" : "created",
"payer" : {
"payment_method" : "paypal"
},
"transactions" : [
{
"amount" : {
"total" : "12.00",
"currency" : "USD"
},
"description" : "",
},
"related_resources" : [ ]
}
],
"create_time" : "2018-08-24T07:48:30Z",
"links" : [
{
"rel" : "execute",
"method" : "POST"
}
],
"httpStatusCode" : 201
}
The Code I am using for this purpose
The above object is stored in the transaction variable that i am getting from paypal api and pushing in the payments array
var newPayment = {
$push:{
payments:{
transaction
}
}
}
Advertiser.updateOne({_id:req.user.id},newPayment,function(err,rec){
if(err) throw err;
})
The objects that are stored in mongodb are like
payments:[
{ transaction:{object} },
{ transaction:{object} },
{ transaction:{object} }
]
But i want to store objects like
payments:[
{object},
{object},
{object}
]

After a lot of time waste i found out the answer to this problem by myself i only need to remove the extra brackets in the push query
Instead of this
var newPayment = {
$push:{
payments:{
transaction
}
}
}
I needed that
var newPayment = {
$push:{
payments:transaction
}
}

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' :

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

Query on array of array object in mongodb

Following is my product collection in mongodb..
{
"_id" : ObjectId("56d42389db70393cd9f47c22"),
"sku" : "KNITCHURI-BLACK",
"options" : [
{
"sku" : "KNITCHURI-BLACK-M",
"stores" : [
{
"code" : "6",
"quantity" : 0
},
{
"code" : "10",
"quantity" : 26
}
],
"ean_code" : "2709502",
"size" : "M"
},
{
"sku" : "KNITCHURI-BLACK-S"
"stores" : [
{
"code" : "6",
"quantity" : 0
},
{
"code" : "10",
"quantity" : 30
}
],
"size" : "S"
}
]
}
want query on where { 'options.stores.code' : '6' } and { 'options.stores.quantity' : { $gt : 0 } }, How i query on this collection then i got response? Kindly help on this issue..
Here is the two approaches to get documents in Mongoose.
You can change the Mongo query if required as given in the various answers. I have just used your approach for Mongo query.
Approach 1 - Using cursor - Recommended Approach
Approach 2 - Using Query
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var Store = new Schema({
code : String,
quantity : Number
});
var Option = new Schema({
sku : String,
stores : [ Store ],
ean_code : String,
size : String
});
var productSchema = new Schema({
_id : ObjectId,
sku : String,
options : [ Option ]
});
var Product = mongoose.model('product', productSchema, 'product');
console.log("Cursor Approach #1");
var cursor = Product.find({
'options.stores' : {
$elemMatch : {
code : '6',
quantity : {
$gt : 0
}
}
}
}).cursor();
console.log("Curosr Results***************************************");
cursor.on('data', function(doc) {
console.log("Getting doc using cursor ==========>" + JSON.stringify(doc));
});
cursor.on('close', function() {
console.log("close the cursor");
});
console.log("Query Approach #2");
var query = Product.find({
'options.stores' : {
$elemMatch : {
code : '6',
quantity : {
$gt : 0
}
}
}
});
console.log("Query Results***************************************");
query.exec(function(err, doc) {
if (err) {
console.log(err);
}
console.log("Getting doc using query ==========>" + JSON.stringify(doc));
});
I think you need to unwind options
db.product.aggregate( [
{ $unwind: "$options" }
{ $match: { 'options.stores.code' : '6','options.stores.quantity' : { $gt : 0 }}
] )
As far as I understand the question, you want to find a products that are in stock in stores with code 6. The following query does that:
db.collection.find({"options.stores" : {$elemMatch: {"code" : "6", "quantity" : {$gt : 0}}}});

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