I am adding MongoDB into my discord bot, I have it set so when something happens it does
await ticketSchema.findOneAndUpdate(
{
$inc: {
ticketNumber: 1
}
}
)
That all works fine, its when I try to find it later that it doesn't work. I am trying to find the ticketNumber no matter what the number is so if its 16 it will show 16 if its 50 it will show 50 and so on. It would be great if I can store whatever the ticketNumber is when I find it into a variable.
This is what I currently have to try and find it not sure what to do lol im new to mongo and js
let result = ticketSchema.find({
ticketNumber: [42]
})
CodePudding user response:
There are multiple ways to get the last value of the increment:
-Get the total number of documents: (not really recommended)
By getting the total number of documents(with appropriate filtering opened/closed) you would have the value of the last increment since you are incrementing every time you add a document.
db.collection.count()
-Get the latest inserted document: (recommended)
The last document inserted will hold the value of your needed increment.
There are a couple of ways to implement this:
db.collection.find().skip(db.collection.count())
or
db.collection.find().sort({ticketNumber:-1}).limit(1)
Note: in order to select specific field you can specify them in the find function.
example:
db.collection.find({}, { ticketNumber: 1, _id: 0}).sort({ticketNumber:-1}).limit(1)
CodePudding user response:
This might help:
let result = await ticketSchema.find({ ticketNumber: { $in: [ 42 ] } })
the above is to find all documents where ticketNumber includes the number 42, assuming ticketNumber is an array field which might be why your code is failing (this is how you use the find when trying to find against an array field).
instead try this (I noticed you missed out the await, hope this helps :)):
let result = await ticketSchema.find({
ticketNumber: 42
})
CodePudding user response:
I am not sure if i can understand you well, but what do you mean by
await ticketSchema.findOneAndUpdate(
{
$inc: { ticketNumber: 1 },
}
);
this code is trying to increments the ticketNumber field by one, but you haven't give it any filters.
findOneAndUpdate(filters, update, options )
in order to get a document then use the find():
let value= your Value here;
let result = ticketSchema.find({ticketNumber: value})