I need to push into nested array in node mongoose - node.js

I used node mongoose.
I need to update this array push new item into Breackfast(mealList.foodList.breackfast || any),
I want to add new foodlist by time can you please give me suggestion for how to do,
{
"_id": "5fe43eb44cd6820963c98c32",
"name": "Monday Diet",
"userID": "5f225d7458b48d0fe897662e",
"day": "Monday",
"type": "private",
"mealList": [
{
"_id": "5fe43eb44cd6820963c98c33",
"time": "Breakfast",
"foodList": [
{
"_id": "5fe43eb44cd6820963c98c34",
"foodName": "Eggs",
"Qty": "2",
"calories": "calories",
"category": "category"
}
]
},
{
"_id": "5fe43eb44cd6820963c98c36",
"time": "Lunch",
"foodList": [
{
"_id": "5fe43eb44cd6820963c98c37",
"foodName": "food1",
"Qty": "100g"
},
]
}
],
"createdAt": "2020-12-24T07:09:40.141Z",
"updatedAt": "2020-12-24T07:09:40.141Z",
"__v": 0
}
I tried:
Diet.updateOne(
{ "Diet.mealList._id": req.body.mealId },
// { $push: { "Diet.0.mealList.$.foodList": req.body.foodList } },
{ $push: { foodList: req.body.foodList } }
)

Few Fixes:
convert your string _id to object type using mongoose.Types.ObjectId
remove Diet from first and push object in foodList
Diet.updateOne({
"mealList._id": mongoose.Types.ObjectId(req.body.mealId)
},
{
$push: {
"mealList.$.foodList": req.body.foodList
}
})
Playground

Related

How to bulkWrite decrease quantity in products when order mongodb?

I have table "products" in mongodb example:
{
"_id": "62ab02ebd3e608133c947798",
"status": true,
"name": "Meat",
"type": "62918ab4cab3b0249cbd2de3",
"price": 34400,
"inventory": [
{
"_id": "62af007abb78a63a44e88561",
"locator": "62933b3fe744ac34445c4fc0",
"imports": [
{
"quantity": 150,
"_id": "62aefddcd5b52c1da07521f2",
"date_manufacture": "2022-03-01T10:43:11.842Z",
"date_expiration": "2023-05-20T10:43:20.431Z"
},
{
"quantity": 200,
"_id": "62af007abb78a63a44e88563",
"date_manufacture": "2022-04-01T10:45:01.711Z",
"date_expiration": "2023-05-11T10:45:06.882Z"
}
]
},
{
"_id": "62b3c2545a78fb4414dd718f",
"locator": "62933e07c224b41fc48a1182",
"imports": [
{
"quantity": 120,
"_id": "62b3c2545a78fb4414dd7190",
"date_manufacture": "2022-03-01T01:30:07.053Z",
"date_expiration": "2023-05-01T10:43:20.431Z"
}
]
}
],
}
I want to decrease quantity in one locator by id in imports of inventory with multiple product (bulkWrite). And can I decrease quantity sort by date_expiration?
Example: when customer order product with quantity 300 and locator 62933b3fe744ac34445c4fc0, I want to product update belike:
{
...
"name": "Meat",
"price": 34400,
"inventory": [
{
"_id": "62af007abb78a63a44e88561",
"locator": "62933b3fe744ac34445c4fc0",
"imports": [
{
"quantity": 50,
"_id": "62aefddcd5b52c1da07521f2",
"date_manufacture": "2022-03-01T10:43:11.842Z",
"date_expiration": "2023-05-20T10:43:20.431Z"
}
]
},
{
"_id": "62b3c2545a78fb4414dd718f",
"locator": "62933e07c224b41fc48a1182",
"imports": [
{
"quantity": 120,
"_id": "62b3c2545a78fb4414dd7190",
"date_manufacture": "2022-03-01T01:30:07.053Z",
"date_expiration": "2023-05-01T10:43:20.431Z"
}
]
}
],
}
Thank you so much!
You should refactor your schema as nesting array as it is considered an anti-pattern and introduces unnecessary complexity to query.
One of the options:
db={
"products": [
{
"_id": "62ab02ebd3e608133c947798",
"status": true,
"name": "Meat",
"type": "62918ab4cab3b0249cbd2de3",
"price": 34400,
"inventory": [
"62af007abb78a63a44e88561",
"62b3c2545a78fb4414dd718f"
]
}
],
"inventory": [
{
"_id": "62af007abb78a63a44e88561",
"locator": "62933b3fe744ac34445c4fc0",
"imports": [
{
"quantity": 150,
"_id": "62aefddcd5b52c1da07521f2",
"date_manufacture": ISODate("2022-03-01T10:43:11.842Z"),
"date_expiration": ISODate("2023-05-20T10:43:20.431Z")
},
{
"quantity": 200,
"_id": "62af007abb78a63a44e88563",
"date_manufacture": ISODate("2022-04-01T10:45:01.711Z"),
"date_expiration": ISODate("2023-05-11T10:45:06.882Z")
}
]
},
{
"_id": "62b3c2545a78fb4414dd718f",
"locator": "62933e07c224b41fc48a1182",
"imports": [
{
"quantity": 120,
"_id": "62b3c2545a78fb4414dd7190",
"date_manufacture": ISODate("2022-03-01T01:30:07.053Z"),
"date_expiration": ISODate("2023-05-01T10:43:20.431Z")
}
]
}
]
}
You can then do something relatively simple. Use $sortArray to sort the date_expiration and start to iterate through the arrays using $reduce.
db.inventory.aggregate([
{
$match: {
locator: "62933b3fe744ac34445c4fc0"
}
},
{
"$set": {
"imports": {
$sortArray: {
input: "$imports",
sortBy: {
date_expiration: 1
}
}
}
}
},
{
$set: {
result: {
"$reduce": {
"input": "$imports",
"initialValue": {
"qtyToDecrease": 300,
"arr": []
},
"in": {
"qtyToDecrease": {
$subtract: [
"$$value.qtyToDecrease",
{
$min: [
"$$value.qtyToDecrease",
"$$this.quantity"
]
}
]
},
"arr": {
"$concatArrays": [
"$$value.arr",
[
{
"$mergeObjects": [
"$$this",
{
"quantity": {
$subtract: [
"$$this.quantity",
{
$min: [
"$$value.qtyToDecrease",
"$$this.quantity"
]
}
]
}
}
]
}
]
]
}
}
}
}
}
},
{
$set: {
imports: "$result.arr",
result: "$$REMOVE"
}
},
{
"$merge": {
"into": "inventory",
"on": "_id"
}
}
])
Mongo Playground
Here is another version that keeps your original schema. You can see it is much more complex.

MongoDb findOneAndUpdate does not update specific document

I'm having trouble getting and updating the only document that matches filter in nest array of objects in mongoose, I'm using the findOneAndUpdate query in mongoose.
This is my data:
{
"_id": "62e87e193fe01f5068f9ae11",
"year": "2023",
"month": "1",
"department_id":"62e387d39ffb6ada6c590fbf",
"blocks": [
{
"name": "CEEDO Schedule Block",
"days": [
{
"day": 2,
"employees": [
{
"employee_id":"62cf92fb3a790000170062e3",
"schedule_type": "Day Off"
},
{
"employee_id": "62cf92fb3a790000170062e2",
"schedule_type": "Shifting"
},
{
"employee_id": "62cf92fb3a790000170062e4",
"schedule_type": "Regular"
}
],
"_id": "62e87e193fe01f5068f9ae13"
},
{
"day": 6,
"employees": [
{
"employee_id": "62cf92fb3a790000170062e3",
"schedule_type": "Day Off"
},
{
"employee_id": "62cf92fb3a790000170062e2",
"schedule_type": "Shifting"
},
{
"employee_id":"62cf92fb3a790000170062e4",
"schedule_type": "Regular"
}
],
"_id": "62e87e193fe01f5068f9ae14"
}
],
"_id": "62e87e193fe01f5068f9ae12"
}
]
}
And here is my query:
const update_block = await schedule_model.findOneAndUpdate({'blocks.days._id': '62e87e193fe01f5068f9ae13'},
{
$set: {"days":req.body.days, "employees":req.body.employees}
}
);
Thanks in advance.
try change '62e87e193fe01f5068f9ae13' to mongoose.Types.ObjectId('62e87e193fe01f5068f9ae13')
I finally found the answer by using the arrayFilter function in mongoose:
const update_block = await schedule_model.updateOne({
"_id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae11')
}, {
"$set": {
"blocks.$[i].days.$[j].day": 31
}
}, {
arrayFilters: [{
"i._id":mongoose.Types.ObjectId('62e87e193fe01f5068f9ae12')
}, {
"j._id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae14')
}]
})
console.log(update_block)
Thank you.

Use Mongoose aggregate to fetch object inside of an array

Here is my MongoDB schema:
{
"_id": "603f23ff6c1d862e5ced9e35",
"reviews": [
{
"like": 0,
"dislike": 0,
"_id": "603f23ff6c1d862e5ced9e34",
"userID": "5fd864abb53d452e0cbb5ef0",
"comment": "Not so good",
},
{
"like": 0,
"dislike": 0,
"_id": "603f242a6c1d862e5ced9e36",
"userID": "5fd864abb53d452e0cbb5ef0",
"comment": "Not so good",
}
]
productID:"hdy6nch99dndn"
}
I want to use aggregate to get the review object of a particular id. I tried but not with any success.
Here is my code:
ProductReview.aggregate([
{ $match: { productID: productID } }
])
$match
$unwind
db.collection.aggregate([
{
$match: {
productID: 1
}
},
{
$unwind: "$reviews"
},
{
$match: {
"reviews._id": 2
}
}
])
Output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"productID": 1,
"reviews": {
"_id": 2,
"comment": "second comment",
"dislikes": [
{
"userID": 3
},
{
"userID": 4
}
],
"likes": [
{
"userID": 1
},
{
"userID": 2
}
]
}
}
]
Mongo Playground: https://mongoplayground.net/p/qfWS1rCuMfc

Unwind inside lookup in Mongoose

I have 2 entities to merge: Customer and Feedback. Feedback contains an embedded array of upvotes (Upvote)
A customer is not able to upvote more than once for a specific feedback.
What I would like to achieve is - given a specific feedback id - get the complete list of customers with an additional virtual attribute that states whether he/she upvoted the given feedback.
Customer.aggregate(
[
{
$match: { company_id: new ObjectID(req.user.company_id) }
},
{
$lookup: {
from: 'feedbacks',
let: { 'c_id': '$_id' },
pipeline: [
{
$unwind: '$upvotes'
},
{
$match: { $expr: { $eq: ['$upvotes.customer_id._id', '$$c_id'] } }
}
],
as: 'upvotes'
}
}
],
function(err, customers) {
if (err) {
console.log(err);
res.status(400).send(err);
} else {
res.send({ customers });
}
}
);
To do that I have to look through the list of upvotes for that specific feedback and, then, join it with the customer table using the customer_id.
The above mentioned approach does not work. Any suggestion what I am doing wrong?
Sample data (Feedback)
{
"size": 0,
"points": 50,
"status": "open",
"potential": 0,
"real": 5000,
"_id": "5c3d033271ceb7edc37d156c",
"title": "Custom Invoice Templates",
"description": "Provide an editor to create custom invoices.",
"owner_id": {
"_id": "5c3b684f7cec8be977c2a465",
"email": "maurizio#acme.com"
},
"company_id": "5c3b684f7cec8be977c2a462",
"project_id": "5c3b68507cec8be977c2a468",
"upvotes": [
{
"_id": "5c3fa5b371ceb7edc37d159a",
"comments": "bbbb",
"priority": "should",
"customer_id": {
"size": 0,
"potential": 0,
"real": 5000,
"_id": "5c3b68507cec8be977c2a485",
"name": "Oyomia Ltd."
},
"owner_id": {
"_id": "5c3b684f7cec8be977c2a465",
"email": "maurizio#acme.com"
}
}
],
"updatedAt": "2019-01-16T21:44:19.215Z",
"createdAt": "2019-01-14T21:46:26.286Z",
"__v": 0
}
Sample data (Customer)
{
"size": 0,
"potential": 0,
"real": 5000,
"_id": "5c3b68507cec8be977c2a485",
"name": "Oyomia Ltd.",
"contact": {
"_id": "5c40f8de71ceb7edc37d15ab",
"name": "Nick Page",
"email": "np#oyoma.com"
},
"company_id": "5c3b684f7cec8be977c2a462",
"deals": [
{
"value": 5000,
"_id": "5c3b68507cec8be977c2a487",
"name": "Armour batch",
"status": "won",
"type": "non_recurring",
"updatedAt": "2019-01-13T16:33:20.870Z"
}
],
"__v": 0,
"updatedAt": "2019-01-17T21:51:26.877Z"
}

Mongoose how to select certain object in embedded array

I had been searching around and still not able to find the correct answer.
Basically I have the below data model in mongodb
{
"_id": {
"$oid": "565db83bcd7bef020b1bdae8"
},
"userId": {
"$oid": "5653a3267827f178214918fc"
},
"targetUser": [
{
"userId": {
"$oid": "564663a5c0aefc151625b5e2"
},
"status": "Approved",
"_id": {
"$oid": "565db83bcd7bef020b1bdaea"
}
},
{
"userId": {
"$oid": "564548249bb75c600ff94cdd"
},
"status": "Sent",
"_id": {
"$oid": "565db884cd7bef020b1bdaed"
}
}
]
},
{
"_id": {
"$oid": "565db884cd7bef020b1bdaec"
},
"userId": {
"$oid": "564548249bb75c600ff94cdd"
},
"targetUser": [
{
"userId": {
"$oid": "5653a3267827f178214918fc"
},
"status": "Pending",
"_id": {
"$oid": "565db884cd7bef020b1bdaee"
}
}
]
}
How can I only return the follow data???
{
"userId": {
"$oid": "5653a3267827f178214918fc"
},
"targetUser": [
{
"userId": {
"$oid": "564663a5c0aefc151625b5e2"
},
"status": "Approved",
"_id": {
"$oid": "565db83bcd7bef020b1bdaea"
}
},
}
I had use the below code, but the result is return null
Connection.aggregate([
{$match:{userId:'5653a3267827f178214918fc'}},
{$unwind:'$targetUser'},
{$match:{'targetUser.status':'Approved'}},
{$group:{
_id:'$_id',
targetUser:{
$push:{
status:'$targetUser.status'
}
}
}}
],function(err,connections){
console.log(connections);
console.log(err);
})
Thank you so much for the help
From what I see, you don't need to aggregate, a simple find with a projection parameter will return what you need.
Connection.findOne({
userId: new ObjectId("5653a3267827f178214918fc")
}).select({
targetUser: {
$elemMatch: { status: "Approved" }
}
}).exec(callback);
But if you have more fields than userId and targetUser, you'll need to add them in the second parameter like this
Connection.findOne({
userId: new ObjectId("5653a3267827f178214918fc")
}).select({
targetUser: {
$elemMatch: { status: "Approved" }
},
oneMoreField: 1,
anotherField: 1
}).exec(callback);

Resources