"$pull" doesn't delete the embedded documents of mongoose array - node.js

My mongo schema is as below:
resourceId: {
type: String,
},
resourceName: {
type: String,
},
dateAndValue: [
{
date: { type: Date },
value: { type: Number },
},
],
Once data is added to the "dateAndValue" array, I want to remove all objects in the array that includes '0' as the value. This is the code I used for it but it doesn't seem to work:
await QuantumResourcesManpowerAdmin.updateMany(
{ resourceId: qrmaRecord.resourceId },
{
$pull: {
dateAndValue: {
$elemMatch: { value: 0 },
},
},
},
{ multi: true }
);

Found the answer, $elemMatch should be removed from the above code. So,
await QuantumResourcesManpowerAdmin.update(
{ resourceId: qrmaRecord.resourceId },
{
$pull: {
dateAndValue: {
value: 0,
},
},
},
{ safe: true, multi: true }
);
would work without any issue

Related

Mongoose, update a nested object inside a nested object

i'm trying to update an object that is inside an array that is nested inside an array my schema is the following:
const quizzerSchema = mongoose.Schema(
{
title: {
type: String,
},
imgUrl: {
type: String,
},
SKU: {
type: String,
},
topics: [
{
topicTitle: { type: String },
questions: [
{
section: { type: String },
setup: { type: String },
question: { type: String },
correct: { type: String },
answer: { type: String },
note: { type: String },
questionNumber: { type: String },
a: { type: String },
b: { type: String },
c: { type: String },
d: { type: String },
e: { type: String },
},
],
},
],
},
{
timestamps: true,
}
);
I want to be able to update the values of a specific object that inside the questions array.
I was able to update the object that is inside the topics array, but now I need to go a level deeper
This is how I am updating the first nested level (Object inside topics)
let updateTopic = await Quizzer.findOneAndUpdate(
{ _id: bookid, 'topics._id': topicid },
{
$set: {
'topics.$.topicTitle': topicTitle,
},
}
);
But I don't know how to access a level deeper.
Any help would be super appreciated
You can update specific nested value using arrayFilters as below:
db.collection.update({},
{
$set: {
"topics.$[x].questions.$[y].d": "New_Value"
}
},
{
arrayFilters: [
{
"x.questions": {
$exists: true
}
},
{
"y.c": "2"
}
]
})
Explained:
Define 2x arrayFilters x & y in the arrayFilter section to identify the nested element
Use in the $set part the filters to update the nested field with key "d" in the example
Playground

How can I query data between date range in array mongoose using express

I'm trying to query for multiple dates in date ranges in mongoose.
member: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Member",
},
point: {
type: Array,
},
recommended: [
{
member: {
type: mongoose.Schema.Types.ObjectId,
ref: "Member",
},
money: { type: Number },
date: {
type: Date,
default: new Date(),
},
},
],
matching: {
type: Array,
},
this is my model
{ const { date } = req.body;
let start = new Date(date[0]);
let end = new Date(date[1]); }
let result = await Income.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.params.id),
recommended: { $elemMatch: { $gt: start, $lt: end } },
},
},
{
$project: {
recommended: {
$filter: {
input: "$recommended",
as: "item",
cond: {
$and: [
{ $gt: ["$$item.date", start] },
{ $lt: ["$$item.date", end] },
],
},
},
},
},
},
]);
I send date from react antd date picker date: ["2022-06-20", "2022-06-25"]
this is controller
I don't understand why it's won't work what is the problem it's no error
api return empty array

How to Update many elements in mongoose array which has embedded documents

I have this mongoose model
resourceId: {
type: String,
},
resourceName: {
type: String,
},
dateAndValue: [
{
date: { type: Date },
value: { type: Number },
},
],
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project',
},
I want to update all value fileds of dateAndValue array elemets to "0" of a given resourceId, given project within a given date range!
await QuantumResourcesManpowerAdmin.updateMany(
{
project,
resourceId,
'dateAndValue.date': { $gte: startDate, $lte: endDate },
},
{
$set: {
'dateAndValue.$.value': 0,
},
},
{ upsert: true }
);
res.status(200).json({ success: true });
This is the code I used for it. It returns success but does not do any update.
All inputs are correct, something is wrong with only the updateMany query, all other functions work!
await QuantumResourcesManpowerAdmin.updateMany(
{
project,
resourceId,
'dateAndValue.date': { $gte: startDate, $lte: endDate },
},
{
$set: {
'dateAndValue.$[element].value': 0,
},
},
{arrayFilters:[{'element.date':{$gte: startDate, $lte: endDate }}] ,upsert: true }
);
res.status(200).json({ success: true });

nodejs / mongoDb: update many fields in one request

how can I update many orderStatus instead of only one?
request.body.type is by default string and contains only one type;
and when isCompleted for the type go true I want even for previous enum index isCompleted go true
is it possible or do I need to modify it in the front-end?
here is the code
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
orderStatus: [
{
type: {
type: String,
enum: ["ordered", "packed", "shipped", "delivered"],
default: "ordered",
},
date: {
type: Date,
},
isCompleted: {
type: Boolean,
default: false,
},
},
],
}
exports.updateOrder = (req, res) => {
Order.updateOne(
{ _id: req.body.orderId, "orderStatus.type": req.body.type },
{
$set: {
"orderStatus.$": [
{ type: req.body.type, date: new Date(), isCompleted: true },
],
},
}
).exec((error, order) => {
Hey You can use updateMany() operation
db.collection.updateMany(
<query>,
{ $set: { status: "D" }, $inc: { quantity: 2 } },
...
)

Unable to push object into array in Mongodb collection but Id is inserted

I am using comment array in my schema as fallows. I want to push comments data into that comment array using nodejs api
var Schema = mongoose.Schema;
var myfeeds = new Schema({
title: {
type: String,
required: true
},
feed: {
type: String,
required: true
},
createdBy: {
type: String,
required: true,
unique: true
},
createdDate: {
type: Date,
required: true,
default: Date.now()
},
comment: [
{
commentBy: {
type: String
},
commentText: {
type: String
},
createdDate: {
type: Date
}
}
],
likes: [
{
likesCount: {
type: Number,
required: false
},
likeBy: {
type: String,
required: false
}
}
]
});
I want to push object to this comment array. so, for that I did in this way please tell me if anything wrong in this
let _id = req.body.id;
let commentBy = req.body.commentedBy;
let commentedText = req.body.commentedText;
let commentedDate = req.body.commentedDate;
let data = {
commentBy: commentBy,
commentText: commentedText,
createdDate: commentedDate
};
MyFeeds.findByIdAndUpdate(
{ _id: _id },
{
$push: {
comment: data
}
}
)
.then((result) => {
res.status(200).json({
status: result
});
})
.catch((err) => {
res.status(500).json({
status: 'invalid',
err: err
});
});
but only id are inserted into that comment array but not the required content
"comment": [
{
"_id": "5badfd092b73fa14f4f0aa7c"
},
{
"_id": "5badfd102b73fa14f4f0aa7d"
},
{
"_id": "5badfd142b73fa14f4f0aa7e"
},
{
"_id": "5badfd31500fb11bb06b4c8a"
},
{
"_id": "5badfd35500fb11bb06b4c8b"
},
{
"_id": "5badff3d439a151190d62961"
}
],

Resources