I have Messages collection and I removed insecure package. I want to insert new document into the collection. Is it possible to update current document before insertion?
This an example that does not work of course:
Messages.allow({
insert: function(userID, doc) {
if (userID == doc.userID) {
// something like this
doc = {
email: Meteor.user().emails[0].address,
message: doc.message,
time: Date.now()
}
return true;
} else {
return false;
}
}
});
As you can see I am getting just doc.message
from the client. But I would like to save also time and user's email into document. How could I do this in Meteor? Are methods the only option?
It might be more preferable to use the collection-hooks package: https://github.com/matb33/meteor-collection-hooks
It would allow you to insert a document both before or after another insert from another collection too.
eg
Messages.before.insert(function (userId, doc) {
doc.createdAt = Date.now();
doc.xxx = false;
});
You can do this but you need to use a deny
because a given allow
isn't guaranteed to run. Give this a try:
Posts.deny({insert: function(userId, doc) {
if (userId === doc.userID) {
_.defaults(doc, {
email: Meteor.user().emails[0].address,
time: Date.now()
});
}
return false;
}});
Have a look at this for a full explanation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.