Mongoose updateMany by id using Node - node.js

is it possible to update array of object by id? ex.:
This is my array:
[
{
"_id": "5fdb614d686e671eb834a409",
"order": 1,
"title": "first"
},
{
"_id": "5fdb61c0686e671eb834a41e",
"order": 2,
"title": "second"
},
{
"_id": "5fdb61d6686e671eb834a424",
"order": 3,
"title": "last"
}
]
and I would like to change only the order of each by ID. I am using Node and I tried to do like that:
router.post("/edit-order", auth, async (req, res) => {
try {
const sections = await Section.updateMany(
req.body.map((item) => {
return { _id: item._id }, { $set: { order: item.order } };
})
);
res.json(sections);
} catch (e) {
res.status(500).json({ message: "Something went wrong in /edit-order" });
}
});
my request body is:
[
{
"_id": "5fdb614d686e671eb834a409",
"order": 2
},
{
"_id": "5fdb61c0686e671eb834a41e",
"order": 3
},
{
"_id": "5fdb61d6686e671eb834a424",
"order": 4
}
]
but as a result, I got:
[
{
"_id": "5fdb614d686e671eb834a409",
"order": 4,
"title": "first"
},
{
"_id": "5fdb61c0686e671eb834a41e",
"order": 4,
"title": "second"
},
{
"_id": "5fdb61d6686e671eb834a424",
"order": 4,
"title": "last"
}
]
so, it change every order by the last value of request array. Any ideas how could I manage that. If you know any other solution feel free to share, all what I need is to change order only by id.

Well, since you have a different value of order for each item, you'll need to do a bulkWrite.
router.post('/edit-order', auth, async (req, res) => {
try {
const writeOperations = req.body.map((item) => {
return {
updateOne: {
filter: { _id: item._id },
update: { order: item.order }
}
};
});
await Section.bulkWrite(writeOperations);
res.json(req.body);
} catch (e) {
res.status(500).json({ message: 'Something went wrong in /edit-order' });
}
});
If you had a single value of order to all the items, you could've used updateMany along with $in.
router.post('/edit-order', auth, async (req, res) => {
try {
const sectionsIds = req.body.map((item) => {
return item._id;
});
const sections = await Section.updateMany(
{ _id: { $in: sectionsIds } },
{ order: 'A single value for all sections in body' }
);
res.json(sections);
} catch (e) {
res.status(500).json({ message: 'Something went wrong in /edit-order' });
}
});

Related

How to compare a string with a value inside of object in mongoDB & Node.js

i am receiving a string "city" from "req.body"
my function:
async function searchProject(req: Request, res: Response) {
const { code, archiveNumber, air, city, municipality, origin } = req.body;
console.log(city);
try {
const projects = await Project.find({
$or: [
{ code: { $regex: code ?? "" } },
{ archiveNumber },
{ air },
{
city: {
$in: [city, "$city.value"],
},
},
{ municipality },
{ origin },
],
});
if (!projects)
return res.status(400).json({ message: "Pas de projet trouvée" });
res.status(200).json(projects);
} catch (err) {
console.log(err);
res.status(500).json({ message: "Server Error" });
}
}
i am using $or operator to get projects that matches at least on the values that receive from "req.body", all other values seem to work but "city".
in my document, here is how city looks like:
"city": [
{
"id": "62ed0121f58a5ed78ac05a85",
"value": "City 1"
}
],
now how can i compare a "city" which i get from "req.body" with "city.value" ?
Solved!!!
i tried:
const projects = await Project.find({
$or: [
{ code: { $regex: code ?? "" } },
{ archiveNumber },
{ air },
{ municipality },
{ origin },
],
}).elemMatch("city", {
value: city,
});
and it worked
thanks to
Siddhesh Khadapkar

How to remove an object from array of objects in mongoose?

I have this data and I want to remove a given movie based on its id/title
"_id": "604184234a2f37156cec63ca",
"name": "Jacob Tremblay",
"description": "Jacob Tremblay is a Canadian actor. He made his film debut as Blue in the live action animated film",
"born": "06051993",
"bornCountry": "Usa",
"movies": [
{
"movie": {
"_id": "604184384a2f37156cec63cb",
"title": "Luca",
"__v": 0,
"id": "604184384a2f37156cec63cb"
},
"role": "Luca"
}
],
"__v": 0
}
In documentation it says I can achieve this using the $pull, but im having trouble to figure it out how its done. My controller method
const removeMovieForActor = async (req, res, next) => {
try {
await Actor.updateOne(
{ _id: req.params.id },
{ $pull: { movies: { title: req.body.movie }}},
{ multi: true }
)
res.status(200).json({ success: true, data: 'ok' })
} catch (error) {
res.status(400).json({ success: false, error: error })
}
}

How to pick a subdocument with its id?

I'm trying to get a subdocument (nested in array) by its id, but I still get the whole document.
router.get("/book/:libraryid/:bookid", (req, res) => {
Library.findOne({ _id: req.params.libraryid, "book._id": req.params.bookid})
.then(result => {
console.log(result); //shows all subdocument
});
});
How can I just pick out the subdocument with its id?
Schema:
{
"_id": {
"$oid": "12345"
},
"libaryName": "A random libary",
"Books": [
{
"_id": {
"$oid": "1"
}
"bookTitle": "Example",
"TotalPages": "500"
},
{
"_id": {
"$oid": "2"
}
"bookTitle": "Delete Me",
"TotalPages": "400"
}
]
}
Use the following and it should return you the document with only filtered book based on bookId.
router.get("/book/:libraryid/:bookid", (req, res) => {
Library.findOne({ _id: req.params.libraryid}, {"books": {"$elemMatch": {_id: req.params.bookid}}})
.then(result => {
console.log(result); //shows all subdocument
});
});

Delete id within nested array

So far I can only manage to delete the first id (in this case the id with "12345").
Im trying to delete the row with id 2 within books-array
Libary Table:
{
"_id": {
"$oid": "12345"
},
"libaryName": "A random libary",
"Books": [
{
"_id": {
"$oid": "1"
}
"bookTitle": "Example",
"TotalPages": "500"
},
{
"_id": {
"$oid": "2"
}
"bookTitle": "Delete Me",
"TotalPages": "400"
}
]
}
My delete code:
router.delete('/:id', (req, res) => {
Libary.remove({ _id: req.params.id })
.then(() => {
//redirect
});
});
How can I reach and delete the book row where the id is 2?
You need to use $pull opertator
router.delete('/:id', (req, res) => {
Libary.update({ _id: req.params.id }, //This is the Id of library Document
{ $pull: { "Books": {"_id":2) } } }) // This will be the Id of book to be deleted
.then(() => {
//redirect
});
});
Hope it helps.
You need to use $pull:
Library.update(
{ },
{ $pull: { Books: { _id: 2 } } }
)

Create and update field Mongoose NodeJs

{
"_id": {
"$oid": "5a4e5b1d09fb590058bfdf86"
},
"name": "ProjectStore",
"imageURL": "none",
"longitude": 0,
"latitude": 0,
"rating": 5,
"leads": [
{
"customerId": "5a0c57db65a4931768716566",
"customerName": "testuser",
"interested": "testuser",
"_id": {
"$oid": "5a4e5b5409fb590058bfdf88"
}
}
],
"items": [
{
"name": "chat",
"categoryID": "5a0c2d292235680012bd12c9",
"semiCatID": "5a0c2d5f2235680012bd12cb",
"_id": {
"$oid": "5a4e5b3009fb590058bfdf87"
}
}
],
"__v": 2
}
I added my DB log, I try to write query that will let me update/push information to "LeadStatus".
This varible should be inside each object in the "leads" array.
I have the keys for the main id "5a4e5b1d09fb590058bfdf86"
I have the second key for the specific lead "5a4e5b5409fb590058bfdf88"
I just dont know how to write the query, for now i got this.... and got error.
Store.update(
{ _id: req.body.store._id, 'leads._id': 'req.body.lead._id', },
{ $set: { 'leads.$.LeadStatus': 'open' }, },
(err, result) => {
if (err) {
res.status(500)
.json({ error: 'Unable to update leads.', });
} else {
res.status(200)
.json(result);
}
}
);
Please Help,
Thanks.
I'm assuming you want the updated doc returned (you can choose to not do so as well, switch option new to false). You have to assign an object the value that you're updating and provide all the fields within the subfield you're updating, otherwise it will remove everything else. That's why you have to do a findOne first:
return Store.findOne({ '_id': "5a4e5b1d09fb590058bfdf86" })
.then((store) => {
if (!store) { // patient was not found for some reason
throw new Error(`Store id was not found`);
}
const options = {
new: true,
};
const updatedStore = Object.assign({}, store.toObject(), {
leads: [
{
"leadStatus": "open",
"customerId": "5a0c57db65a4931768716566",
"customerName": "testuser",
"interested": "testuser",
"_id": {
"$oid": "5a4e5b5409fb590058bfdf88"
}
}
],
});
return Store.findOneAndUpdate(
{ '_id': req.body.store._id },
{ $set: updatedStore },
options);
});
In case you're curious, you can build pre/virtual hooks off of findOneAndUpdate (no documentation for this), you won't lose anything from not using update.

Resources