Can I get newly inserted id with sequelize insertOrUpdate? - node.js

How can I get newly inserted id with the following sequelize? It currently returns a boolean.
exports.update = async note => entityChildModel.insertOrUpdate(note)
.catch(e => 'Error');

You can use returning : true ( to get back auto generated values ) , but it's only for Postgres :
exports.update = async note => entityChildModel
.insertOrUpdate(note , { returning : true }) // <--- HERE
.catch(e => 'Error');
For more detail : DO READ

Related

How to update many documents on mongo and return that updated document?

How can I update many documents on mongoose and return those updated documents so I then I can pass the updated docs to a different service on my code? This is seems like something simple to do but I'm getting confused on my head on how to implement it
In my current code I just update the documents on batch with updateMany, but as the mongo documentation says the writeConcern returned is just the # of docs updated {n: 0 } not the actual documents.
Current Code:
const checkAndUpdateSubscription = () => {
const filter = {
"payments.0.stripeSubscriptionEndDate": { $lte: today },
hasPaid: true,
};
const update = { $set: { hasPaid: false, isSubscriptionNew: 0 } };
const options = { new: true, useFindAndModify: false };
return new Promise((resolve, reject) => {
ModelModel.updateMany(filter, update, options)
.then((response) => {
console.log('response inside checkAndUpdateSubscription', response)
resolve(response);
})
.catch((error) => {
reject(error);
});
});
};
I would like to change it to something similar to my pseudo code below.
What I would like to do:
const checkAndUpdateSubscription = () => {
const filter = {
"payments.0.stripeSubscriptionEndDate": { $lte: today },
hasPaid: true,
};
const update = { $set: { hasPaid: false, isSubscriptionNew: 0 } };
const options = { new: true, useFindAndModify: false };
return new Promise((resolve, reject) => {
// 1. ModelModel.find where stripeSubscriptionEndDate $lte than today ..etc
// 2. Update the document(s)
// 3. Return the updated document(s)
(//4.) .then(updatedModel => sendUpdateModelToOutsideService(updatedModel))
});
};
I don't know if this is necessary in the context of this question but the checkAndUpdateSubscription method is a function that runs every 1min in my db for all my users (# ~thousands)
You can do those as alternative solutions
(maybe there is simpler way, but those will work i think)
Find the ids
find to get those ids
ids = find(your_filter,project_keep_id_only), and then make ids=[_id1, _id2 ...] an array of the ids
update with filter _id $in ids
update({"_id" : {"$in" : ids}},your_update_set_etc)
find to get the updated documents
docs=find({"_id" : {"$in" : ids}})
*if ids are not too many it will be fine i think
Mark the updated with extra field
on update set one extra field with the update_id
after the update, do a find based on that update_id, to get the documents
and if you want your remove that extra field after
If this run parallel, this extra field could be an array, with many update_ids, that you remove them after you get those documents back.

Delete an income record inside an array object of a user

MongoDB user entry
Controllers code:
module.exports.deleteIncome = (params) => {
return User.findById(params.userId) // I went to the user here
.then((user, err) => {
if(err) return false
user.incomeRecords.remove( "_id": "{params.incomeRecordId}" ) // my delete income record syntax
return user.save()
.then((updateUser, err) => {
return(err) ? false : true
})
})
}
Here's my code, it's not working
Please see the pic i provided
I want to delete the specific income record inside the user's array incomeRecords
Please help thanks =)
You can use the mongodb pull operator. It would look something like this:-
findOneAndUpdate({userid:params.userid},{
$pull:{
incomeRecords:{
_id:<the mongodb id here>
}
}
})
Check out the mongodb docs

How to remove an element from an array included in an Object

I'm trying to build an application, using MongoDB and nodejs.
I have a model Ride, which contains an array of userID called steps. I'd like to delete one userID entry from a Ride specified by its own RideID.
I have tried the following code, but it's not working, an error is always raised
router.post('/quitRide',async (req,res)=>{
let userID = req.body.userID; //userID to be deleted
let rideID = req.body.rideID; //rideID of the Ride we want to access
Ride.find({_id:rideID})
.exec()
.then(t => {
t[0].steps.splice(t[0].steps.indexOf(userID), 1);
res.status(200);
})
.catch(err => res.status(400).json({error : err}))
})
Here's the error I get :
{error: "erreurTypeError: Cannot read property 'indexOf' of undefined"}
It seems like steps are somehow not accessible
Try using $pull, for more go to this link
router.post('/quitRide',async (req,res)=>{
let userID = req.body.userID; // userID to be deleted
let rideID = req.body.rideID; // rideID of the Ride we want to access
Ride.findOneAndUpdate({_id:rideID}, { $pull: { steps: userId } })
.exec()
.then(t => {
// response with success
res.status(200);
})
.catch(err => res.status(400).json({error : err}))
})
You can use the Lodash Remove function to remove the elements from the array.
you can install the npm package by running this command npm i --save lodash.remove and then do the changes in your code.
router.post('/quitRide',async (req,res)=>{
let userID = req.body.userID; //userID to be deleted
let rideID = req.body.rideID; //rideID of the Ride we want to access
Ride.find({_id:rideID})
.exec()
.then(t => {
_.remove(t[0].steps,userID);
console.log(t[0].steps)//which contains your array without userID
res.status(200);
})
.catch(err => res.status(400).json({error : err}))
})
Don't forget to import/require the lodash package and you can find the documentation on below link
https://lodash.com/docs/4.17.14#remove

How to update some data based on array value in Mongoose?

I'd like to update some data in Mongoose by using array value that I've find before.
Company.findById(id_company,function(err, company) {
if(err){
console.log(err);
return res.status(500).send({message: "Error, check the console. (Update Company)"});
}
const Students = company.students;
User.find({'_id':{"$in" : Students}},function(err, users) {
console.log(Students);
// WANTED QUERY : Update company = null from Users where _id = Students[];
});
});
Students returns users._id in array with object inside, and I use that to find users object, and then I want to set null a field inside users object, that field named as "company". How I can do that? Thank you.
From what you posted (I took the liberty to use Promises but you can roughly achieve the same thing with callbacks), you can do something like:
User.find({'_id':{"$in" : Students}})
.then( users =>{
return Promise.all( users.map( user => {
user.company = null;
return user.save()
}) );
})
.then( () => {
console.log("yay");
})
.catch( e => {
console.log("failed");
});
Basically, what I'm doing here is making sure .all() user models returned by the .find() call are saved properly, by checking the Promised value returned for .save()ing each of them.
If one of these fails for some reasons, Promise.all() return a rejection you can catch afterhand.
However, in this case, each item will be mapped to a query to your database which is not good. A better strategy would be to use Model.update(), which will achieve the same, in, intrinsically, less database queries.
User.update({
'_id': {"$in": Students}
}, {
'company': <Whatever you want>
})
.then()
use .update but make sure you pass option {multi: true} something like:
User.update = function (query, {company: null}, {multi: true}, function(err, result ) { ... });

How to create a new document 'if not exists' and return the new document with MongoDB NodeJS native driver

I want to create a new document if it doesn't exist and return the new document once created, however if the document already exists I would like an exception to be thrown.
I think the way I am doing this seems hackish, is there a better means of doing this?
var query = { name: 'guaranteed to be unique' }
var new_doc = { ... }
var col = // the Mongo collection we're using
col.updateOne(
query,
new_doc,
{upsert: true}
)
.then(update => col.findOne({_id, update.result.upserted.pop()._id}))
.then(doc => console.log(doc))
.catch( exception => console.log('that already exists') )
After a lot a searching I found some answers in this post, but here's a clean example with findOneAndUpdate and the returnOriginal property set false
col.findOneAndUpdate(
query,
new_doc,
{ upsert: true, returnOriginal:false }
)
.then(update => update.value)
.then(doc => console.log(doc))

Resources