I am trying to find my record, update it, and save it. I can see the data updated and it can still show the updated data inside the callback of save(). However, when I go to the database, it is actually not updated:
Skills.findOne({ skillsCat: req.body.skillsCat }, (err, gets)=> {
if (err) {
res.send(err)
return
}
if (gets && gets.skillName.indexOf(req.body.skillName) !== -1) {
// Here I update my data
gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
Console.log(gets); // Here I can see the data is updated
return gets.save((err, updated)=> {
Console.log(updated); // Here I can see the data is updated
if (err) { return }
res.json({
message: 'Skill updated successfully',
data: updated
})
})
} else {
return
}
})
Is there anyone encounter similar issues before and help me out with this? Thanks.
Try below code :
gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
Console.log(gets); // Here I can see the data is updated
//Notice that 'fieldname' is the name of actual field in database
gets.markModified('fieldname');
return gets.save((err, updated)=> {
Console.log(updated); // Here I can see the data is updated
if (err) { return }
res.json({
message: 'Skill updated successfully',
data: updated
})
})
Related
I am facing an issue while updating data, the user is not getting updated even after I passed hardcoded data, I'm trying to pass through postman-body-formData but it's not working I'm getting undefined in the result.
User.findByIdAndUpdate({_id: '61f8f3a09cd06463942401'},
{
$set:{
name: 'demoo',
dob: new Date(params.dob),
dom: new Date(params.dom)
}
}, function (error, result) {
logger.info("#edit() : User updated successfully with results = {%j}", result,{});
done(result);
console.log('result',result);
});
}
Try to change approach and update your User manually (make sure that the parent function is declared as async):
try {
const user = await User.findById('61f8f3a09cd06463942401')
if (!user) return res.status(400).send('User not found')
user.name = 'demoo'
user.dob = new Date(params.dob)
user.dom = new Date(params.dom)
await user.save()
done(user);
} catch (err) {
return res.status(500).send('Server error')
}
I am write API in expressjs with Sequence. But I got problem with return value when update!
I follow a tutorial on internet but it got error when num=[1] not num=1 although updating success!
exports.update = (req, res) => {
const { id } = req.params;
Post.update(req.body, {
where: { id }
})
.then((num) => {
if (num === 1) {
res.send({
message: 'Post was updated successfully.'
});
}
else {
res.send({
message: `Cannot update Post with id=${id}. Maybe Post was not found or req.body is empty!`
});
}
})
.catch((err) => {
res.status(500).send({
message: `Error updating Post with id=${id}`
});
});
};
So, what return value after call update method? and how do I solve it? Thanks.
The sequelize document of update is
public static async update(values: object, options: object): Promise<Array<number, number>>
Promise<Array<number, number>>
The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true).
So, it will not return only the number. you need to follow the document.
To resolve
.then((nums) => {
const num = nums[0]
.....
I am trying to make this basic CRM and here i need to see how many times the link has been visited by the client! is there any way i can do that and store ?
Actually I did this, as Ravi Teja said comment.
Added userClicks in the database model in case of mongoose.
(This is nested into another object)
analytics: {
userClicks: {
type: Number,
default : 0
}
}
When any request hits to that URL, I just update that count by one.
app.get('URL', (req, res) => {
//First find document in database
Url.findOne({
$text: {
$search: request.params.shortUrl
}
}).then(url => {
if (url === null) {
return response.status(404).json({
message: "Link in not valid"
});
} else {
//If successfully found, get already stored value and updated with +1, and then update that document.
const _id = url._id
let counterClicks = url.analytics.userClicks;
//Update existing values
counterClicks++;
Url.findByIdAndUpdate({
_id
}, {
$set: {
'analytics.userClicks': counterClicks
}
}).exec().then(url => {
console.log(url);
return response.redirect(302, url.originalUrl);
}).catch(error => {
console.log(error);
});
}
}).catch(error => {
console.log(error);
});
});
You can do this by newer async-await syntax.
From the above's code snippet, we will get idea, How to implement it.
I want to know if there is a way to check if a property is present in a Cloud Firestore document. Something like document.contains("property_name") or if there is a document property exist.
To solve this, you can simply check the DocumentSnapshot object for nullity like this:
var yourRef = db.collection('yourCollection').doc('yourDocument');
var getDoc = yourRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
if(doc.get('yourPropertyName') != null) {
console.log('Document data:', doc.data());
} else {
console.log('yourPropertyName does not exist!');
}
}
})
.catch(err => {
console.log('Error getting document', err);
});
You could use the in operator like in the snippet bellow
const ref = admin.firestore().collection('yourCollectionName').doc('yourDocName')
try {
const res = await ref.get()
const data = res.data()
if (!res.exists) {
if (!("yourPropertyName" in data)) {
// Do your thing
}
} else {
// Do your other thing
}
} catch (err) {
res.send({err: 'Something went terribly wrong'})
}
I think you refer to making a query.
Still there is no way to check if some field is present or not in the Firestore. But you can add another field with value true/false
val query = refUsersCollection
.whereEqualTo("hasLocation", true)
query.get().addOnSuccessListener {
// use the result
}
check out this links for more
https://firebase.google.com/docs/firestore/query-data/queries
How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?
I am trying to put my queries into transaction and I am failing in runtime. Error I am getting is :
Object #<bound> has no method 'transaction'
I tried to follow this "documentation".
In short my model looks like that :
updateOrCreate: function (profile_id, positive,negative) {
var deferred = Q.defer();
Reputation.transaction().findOne().where({profile: profile_id}).then(function (rep) {
if (rep) {
// Reputation logic
rep.save(function (err) {deferred.resolve();});
} else {
// Reputation does not exist. Create.
Reputation.create({profile: profile_id, positive: positive,negative:negative}).exec(function (e, rep) {
deferred.resolve();});
}
}).fail(function (err) {deferred.reject()});
return deferred.promise;
}
any ideas what did I do wrong?
thanks.
w.
This is now supported in sails v1 (not official release yet at June 26, 2017).
You can follow this link for documentation in next.sailsjs.com:
Datastore.transaction()
In doc above is the following example:
sails.getDatastore()
.transaction(function (db, proceed) {
BankAccount.findOne({ owner: req.session.userId }).usingConnection(db)
.exec(function (err, myAccount) {
if (err) { return proceed(err); }
if (!myAccount) { return proceed(new Error('Consistency violation: Database is corrupted-- logged in user record has gone missing')); }
BankAccount.findOne({ owner: req.param('recipientId') }).usingConnection(db)
.exec(function (err, recipientAccount) {
if (err) { return proceed(err); }
if (!recipientAccount) {
err = new Error('There is no recipient with that id');
err.code = 'E_NO_SUCH_RECIPIENT';
return proceed(err);
}
// Do the math to subtract from the logged-in user's account balance,
// and add to the recipient's bank account balance.
var myNewBalance = myAccount.balance - req.param('amount');
// If this would put the logged-in user's account balance below zero,
// then abort. (The transaction will be rolled back automatically.)
if (myNewBalance < 0) {
err = new Error('Insufficient funds');
err.code = 'E_INSUFFICIENT_FUNDS';
return proceed(err);
}
// Update the current user's bank account
BankAccount.update({ owner: req.session.userId })
.set({
balance: myNewBalance
})
.usingConnection(db)
.exec(function (err) {
if (err) { return proceed(err); }
// Update the recipient's bank account
BankAccount.update({ owner: req.param('recipientId') })
.set({
balance: recipientAccount.balance + req.param('amount')
})
.usingConnection(db)
.exec(function (err) {
if (err) { return proceed(err); }
return proceed();
});
});
});
});
}).exec(function(err){
// At this point, we know that, if our code above passed through
// an error to `proceed`, Sails took care of rolling back the
// transaction. Otherwise, it committed it to the database.
if (err && err.code === 'E_INSUFFICIENT_FUNDS') {
return res.badRequest(err);
}
else if (err && err.code === 'E_NO_SUCH_RECIPIENT') {
return res.notFound();
}
else if (err) {
return res.serverError(err);
}
// All done!
return res.ok();
});
The "documentation" you're following is a proposal for how transaction support could be added to Sails. There is no native transaction support in Sails. See this answer for an example of how to use the .query method for the MySQL or Postgres adapters to perform transactions.
Seems they don't support this. You could use something like:
https://github.com/Shyp/pg-transactions
https://github.com/postmanlabs/sails-mysql-transactions