Why mongo updates first element in db despite the condition - mongodb

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

Related

How to delete items by _id using 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 :)

Mongoose findOneAndUpdate() only updates if document already exists, doesn't create new doc if not?

I ran into a problem with my javascript bot, my custom prefixes don't get saved if there isn't yet a custom prefix for that server, if there is though, it does get updated correctly.
await mongo().then(async (mongoose) => {
try {
let newprefix = content.replace(`${prefix}setprefix `, '')
await prefixSchema.findOneAndUpdate({_id: guild.id}, {_id: guild.id, prefix: newprefix})
.then(async () => {
console.log(`updated prefix for guild: ${guild.id}`)
await channel.send(`Succesfully updated prefix for this server to '${newprefix}'`)
message.guild.me.setNickname(`[${newprefix}] - Helix`)
})
.catch(async (err) => {
console.error(`failed to update prefix for guild: ${guild.id}\n${err}`)
await channel.send(`Failed to update prefix.`)
})
console.log("saved to db")
} catch {
console.log("Something went wrong while saving new prefix for a server.")
} finally {
mongoose.connection.close()
}
The bot does print and send that it succesfully updated the prefix, but if there isn't already a document for the guild.id, nothing is saved. What did I do wrong and how can I solve it?
Thanks for reading!
Model.updateOne()
Parameters
[options.upsert=false] «Boolean» if true, and no documents found, insert a new document
MongoDB will update only the first document that matches filter regardless of the value of the multi option.
Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.
Example:
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
please visit https://mongoosejs.com/docs/api.html#model_Model.updateOne for more information.

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 findOneAndUpdate return not updated model

I've 1 little issue. I'm trying update model by findOneAndUpdate method. And this method works unexpected - method update model in DB but return old model (before update)
try {
const updatedLanding = await Landing.findOneAndUpdate({key: req.body.key}, {
$set: {
name: req.body.name,
}
},
).exec((err, result) => {
if (err) {
res.status(422).send({error: err});
return
}
res.send({response: result})
});
}
catch (e) {
res.status(400).send(e)
}
in mongoose query, findOneAndUpdate returns the old record that has been updated, not the updated record, the record has actually been updated, but you can not get the updated result as the query returns the old one by default, if you want to see the updated record you have to issue another query to find the record and get its updated data.
If you update document using findOneAndUpdate() hook, you'll get the old document unless you specify
{ new: true }

In mongo how to get the current position of the record in the table with the total records for pagination?

I'm trying to return create a paginated list. I used graphql to query the data. With my query, I pass the number of records I need (In a variable named first) and the ID of the last fetched record (In a varible called after). Now I managed to write a query (Note that I used mongoose) to fetch the records. Now what I need to do is get the relavant information to perform the pagination like hasNextPage, hasPreviousPage, currentPage and totalPages.
To get most of these information I need to get the total number of records in the database. To do that I need to send another db request.
I also need to know the position of the record in the table. No idea how.
Here's the query:
new Promise((resolve, reject) =>
Company.where('_id')
.gt(after)
.limit(first)
.lean()
.exec((error, doc) => {
if (error) {
reject(error);
}
resolve({
edges: doc,
pageInfo: {
hasNextPage: '...',
hasPreviousPage: '...',
currentPage: '...',
totalPages: '...'
}
});
}))
Any idea how to do this efficiently?
you can try this module mongoose-paginate
here what i uses, for pagination,
var current = req.query.filter.current;
var limit = req.query.filter.limit;
console.log('params.query.filter.current',current);
var skip = Number(limit)*Number(current)-Number(limit);
console.log('skip::',skip);
Cours.find({'attributes.version.status': true}).skip(skip).limit(limit).sort({_id:'asc'}).exec(function (err, resulta) {
if (err) {
console.log('erreur trouverCours');
res.json({
protecteds: err
});
}
console.log('cours ::', resulta);
res.json({
"data": resulta
});
});