Unown Way To Change Parameter Inside Mongoose - node.js

I am having some issues with saving an object parameter into a mongoose map. My collection looks like this. The collection's name is guildtickets:
{
"_id":"813915771067301888",
"maxopenTickets":"5",
"serverticketnum":"2",
"opentickets": {
"850608478229626891": {
"ticketname":"ticket-0001",
"ticketstatus":"open",
"ticketcreatedby":"843644509324705814"
}
},
"__v":0}
I wish to change the ticketstatus parameter to closed, so the result should be "ticketstatus": "closed". So far I am using:
var queryTicketSchema = await GuildTicketsSchema.findOne({
_id: message.guild.id
});
queryTicketSchema.get(`opentickets`).get(`${message.channel.id}`).ticketstatus = 'closed';
The issue with the code above, is that when logging the collection, the ticketstatus parameter is showed as closed, but while in MongoDB compass, the parameter is still listed as open. Any help is appreciated and more than welcome! Tysm!

Try this:
let ticket = await GuildTicketsSchema.findOne({
_id: message.guild.id
});
ticket.get(`opentickets`).get(`${message.channel.id}`).ticketstatus = 'closed';
await GuildTicketsSchema.findByIdAndUpdate(ticket._id, ticket);

Related

Mongoose findOneAndUpdate() using current data

I am try to track the number of downloads per click on a website.
server.js
router.post("/download", async (req, res) => {
let id = req.body.id;
id = parseInt(id);
let doc = await db.findOneAndUpdate({_id: id}, {downloads: 100});
});
Note: This works
But I'm trying to increase the number by 1 each time.
For example: Let's say the current number of downloads is 5, how do I do it that if there's a post request. The number of downloads increases by 1.
const { body: { id } } = req;
const intCasetedId = parseInt(id);
const retrievedDocument = await db.findOneAndUpdate({ id }, { $inc: { downloads: 1 } });
A couple things are happening here.
First I get the id value from the the req argument using a destructuring assignment.
I use only const to ensure I do not mutate variable values.
I also use the object property value shorthand notation to skip '_id' key in the search query argument. Quoting mongoose documentation:
Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).
Then I am using '$inc' operator to increment the downloads field by 1.
I would also highly recommend for you to research eslint

return updated entity with entityRepository

Is there any way to update an entity and return the result of the operation USING entity repository and NOT query Builder?
const result = await this.shipmentRepository.createQueryBuilder('sh')
.update()
.set({ ...infoToUpdate })
.where('shipment_number = :shipmentNumber', { shipmentNumber })
.returning("*")
.execute()
return result.raw[0]
I'm using this ^, this works properly but I want to know if I can do it using this syntaxis
const result = await this.shipmentRepository.update({ shipment_number: shipmentNumber }, infoToUpdate)
TypeORM documentation doesnt say anything about it
Can you help me? Thank u a lot!

How to populate a referenced document from `this` object?

I am using NodeJS, MongoDB, and Mongoose. I am able to populate a referenced document if I use findById(this.id), but not using this directly:
IssuanceSchema.methods.getOrganizationName = async function() {
let issuance = await Issuance.findById(this.id).populate('organization');
console.log(issuance);
let temp = this.populate('organization');
console.log(temp);
console.log(issuance.organization.displayName());
console.log(temp.organization.displayName());
// ...
}
The log shows:
{
_id: 5e849ca9b07ed81bd2eaad89,
organization: {
_id: 5e80a19d8c910f196c11673c,
...
},
}
{
_id: 5e849ca9b07ed81bd2eaad89,
organization: 5e80a19d8c910f196c11673c,
}
SomeName
(node:10231) UnhandledPromiseRejectionWarning: TypeError: temp.organization.displayName is not a function
How can I populate the referenced document directly without the round-about findById?
It seems you are simply missing a call to execPopulate(). In your case that would be:
let temp = this.populate('organization').execPopulate();
Check out the docs:
If you have an existing mongoose document and want to populate some of its paths, you can use the Document#populate() method. Just make sure you call Document#execPopulate() to execute the populate().

findOneAndUpdate with Upsert always inserting a new user

I want to do is update a record and insert it if it doesn't exist with mongoose. Here is my code:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
Users.findOneAndUpdate({email: user.email}, options, {upsert:true}).exec();
}
And:
var promise = Users.upsertUser(user);
promise
.then(function(results){
...
}
.catch(function(err){
...
}
When I execute the promise, each time a new user is created with the same email.
I'm not sure if I'm performing the update incorrectly. I've tried it in the same way but with update and it does not work either.
Can you help me? Thanks!
You need to put the return without the exec:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
return Users.findOneAndUpdate({email: user.email}, options, {upsert:true, new: true});
}
var promise = Users.upsertUser(user);
promise.then(function(results){
if(results) {
console.log(results);
} else {
console.log('!results');
}
}.catch(function(err){
...
}
FYI:
The default is to return the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: {new:true} with the upsert option.
according to your coding what findOneAndUpdate() does is that it finds this document/user's document that you are looking for to edit which in this case what you are using to search for this user's document that you want to edit it's document is with his email. Now your second argument modifies that part of the document that you wanted to modify, but this option has to be attached with some mongodb operators (pay a visit to this link for a list of them: https://docs.mongodb.com/manual/reference/operator/update/) but in your case what you need is the $set operator.so i would modify your code like this:
module.exports.upsertUser = function(user) {
var options =
Users.findOneAndUpdate({email: user.email}, {$set:{
userName : 'Ricardo'
}}, {
returnOriginal: true}).exec();
};
so try the above modification let's see how it works

mongoose, getting object's id after using collection.insert

I'm trying to get the object id after adding it to the db (using collection.insert)
mongoose.model('Persons').collection.insert(person, function(err, newPerson) {
console.log('lets see you', newPerson);
});
and from the console I'm getting only result: { ok: 1, n: 1 } in stand of the new obj, any ideas how can I rich to the new object ?
thanks!
You can use save() here
var Persons = mongoose.model('Persons');
var personJSON = {
..... // persons schema values you want to insert
};
var person = new Persons(personJSON);
var result = yield person.save();
result variable will contain all the fields you inserted along with _id

Resources