How to delete items by _id using mongodb - mongodb

I have a problem trying to delete data by providing an array of id's (got error).
I guess it has something to do with ObjectId. Could you help me fix it?
User.deleteMany({
_id: { $in: ['638207a8b9ebc3ea8f276684',
'63823ffe310abc61b4ee11a0',
'63822a71319517d196af6d59' }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error('Error deleting users'))
I tried to map this array to prepend every item of it with ObjectId but got ObjectId is not found.

Try this..
let userIds = ['638207a8b9ebc3ea8f276684',
'63823ffe310abc61b4ee11a0',
'63822a71319517d196af6d59']
let userObjectIds = userIds.map(e=>Types.ObjectId(e))
User.deleteMany({
_id: { $in: userObjectIds }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error('Error deleting users'))

If the code you pasted above is the exact code you are running, the problem is likely your input ids array syntax. It seems as though you are missing a close square bracket (]). Try this instead:
const userIds = ['638207a8b9ebc3ea8f276684', '63823ffe310abc61b4ee11a0', '63822a71319517d196af6d59']
User.deleteMany({
_id: { $in: userIds }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error(`Error deleting users: ${error}`))
If that doesn't work, you may need to follow Alex's advice by mapping them to ObjectId types. As a side note, it's always good practice to save your input into a variable rather than hard code it. It's also helpful for debugging to log the contents of the error from your catch callback
console.error(`this is my error: ${error}`)
Hope that helps you out, happy coding :)

Related

How to find all the matches in a nested array with the _id with mongoose

This question may be easy for some of you but I can't get how this query works.
In the attached picture: https://i.stack.imgur.com/KzK0O.png
Number 1 is the endpoint with the query I can't get it to work.
Number 2 is the endpoint where you can see how I am storing the object match in the database.
Number 3 is the data structure in the frontend.
Number 4 is the Match mongoose model.
I am trying to get all the matches that have the _id I am sending by param in any of its members array.
I am trying it with $in, but I am not sure how this nested object array property query works.
I am very new at web development and this is quite difficult to me, any help would be highly appreciated, even some documentation for dummies, since I can't understand the one in the official site.
Thanks in advance
router.get("/profile/:_id", (req, res) => {
const idFromParam = req.params._id;
console.log("params", req.params._id);
Match.find({ match: [ { teams: [{ members: $in: [_id: idFromParam ] } ] ] }}).populate("users")
.then((response) => {
res.json(response);
console.log("response", response);
}) })
.catch((err) =>
res.status(500).json({ code: 500, message: "Error fetching", err })
);
});

Why mongo updates first element in db despite the condition

tell me pls why this code updates firs element in db despite the condition. And i couldn't see any logs. Im using NestJs+Typeorm+Mongo
await this.workOrderModel
.updateOne({ createRequestId: 'someMockedVaue' }, { $set: { createFlowTrackingId: 'otherValue' } })
.then((updatedWorkOrder) => {
this.logger.verbose('Updated WorkOrder: %o', updatedWorkOrder);
})
.catch((err) => {
this.logger.error('Error on update WorkOrder: %o', err);
});
I understood what the problem is, if you specify the wrong field in the filter, it takes the first user in the db and changes the data

Validate unique text using Express Validator & Mongoose

I have a mongodb collections named "articles"
I have configured below rules for validating "title" field of article while Updating the record.
validator.body('title').custom( (value, {req}) => {
console.log(value, req.params.id)
return Article.find({ title:value, _id:{ $ne: req.params.id } })
.then( article => {
if (article) {
return Promise.reject('Title already in use');
}
})
})
So basically it should check if "title" should not exists in the collection and it should not be the same ID as the one I am updating.
The line console.log(value, req.params.id) is printing proper Title and ID but the validation is always saying "Title already in use". Even though I use entirely different title that is not used at all.
Any idea what's wrong?
You should use findOne query for better performance and check data is null like as bellow.
validator.body('title').custom( (value, {req}) => {
console.log(value, req.params.id)
return Article.findOne({ title:value, _id:{ $ne: req.params.id } })
.then( article => {
if (article !== null) {
return Promise.reject('Title already in use');
}
})
})
Stupid mistake,
the
if (article) {
is supposed to be
if (article.length) {
And it worked fine.

mongoose post without duplications

I am trying to look at a post/create that does not allow multiple instances in the database(so no duplicates). I looked at the updateOne with an {upsert:true} and this won't work for me because that only works if you have a specific set of data.
example data:
cat:{
name: "jim",
age: 8
}
example model :
cat:{
name: String
}
the code I had :
object.updateOne(req.body,req.body,{upsert:true},function(err,object){
if(err) console.log(err);
res.json(object);
})
}else{
res.json('error: type: '+ req.params.type + 'not found !');
}
but this only works if I add 'age' to my model. due to the {strict:true} policy on the updateOne. and when I use a post I get multiple instances of the same object.
so hopefully someone can help me. ( and if someone knows a better title for this problem , please comment it below). I didn't know how to describe my problem with 1 sentence.
(keep in mind that in reality I have a dataset of 100+ attributes and only need 60). so simply adding age wouldn't help for my dataset. because then I have 40 unused values in my document.
Edit:
after looking at code posted as an answer below i noticed that i made an error in my own code. this is how the code is supose to be :
object.updateOne({},req.body,{upsert:true},function(err,object){
if(err) console.log(err);
res.json(object);
})
}else{
res.json('error: type: '+ req.params.type + 'not found !');
}
Please try using strict:false in update query. They may help to solve your problem.
var data = { fieldOne: 'Test2', fieldTwo: 'Test3' };
var opts = {
upsert: true,
runValidators: false,
strict: false
};
Model.update({}, data, opts)
.then((success) => {
//success
}).catch(() => {
//error
})

MongoDb/Mongoskin - CLEANLY Update entire document w/o specifying properties

All the examples I have seen for MongoDb & Mongoskin for update, have individual properties being updated, like so:
// this works when I specify the properties
db.collection('User').update({_id: mongoskin.helper.toObjectID(user._id)},
{'$set':{displayName:user.displayName}}, function(err, result) {
if (err) throw err;
if (result){ res.send(result)}
});
But what if I wanted the whole object/document to be updated instead:
// this does not appear to work
db.collection('User').update({_id: mongoskin.helper.toObjectID(user._id)}, {'$set':user},
function(err, result){
// do something
}
It returns the error:
// It appears Mongo does not like the _id as part of the update
MongoError: After applying the update to the document {_id: ObjectId('.....
To overcome this issue, this is what I had to do to make things work:
function (req, res) {
var userId = req.body.user._id
var user = req.body.user;
delete user._id;
db.collection('User').update({_id: mongoskin.helper.toObjectID(userId)},
{'$set':user}, function(err, result) {
if (err) throw err;
console.log('result: ' + result)
if (result){ res.send(result)}
});
})
It there a more elegant way of updating the whole document, instead of hacking it with:
delete user._id
If you want to update the whole object, you do not need a $set. I am not aware of mongoskin, but in shell you would do something like:
var userObj = {
_id: <something>
...
};
db.user.update({_id: user._id}, user);
Which I think can be translated in your mongoskin in the following way.
db.collection('User').update({_id: user._id}, user, function(){...})
But here is the problem. You can not update _id of the element in Mongo. And this is what your error tells you. So you can remove the _id from your user object and have it separately. Search by this separate _id and update with a user object without _id.