This doesn't work, but hopefully this and the mouthful of a title gets the point across
function addToDB(account_id)
{
obj = {};
if (!Accounts.findOne({account_id: account_id})) obj.createdAt = new Date().valueOf();
obj.account_id = account_id;
Accounts.upsert({account_id: account_id}, {$set: obj});
}
I need to use the account_id instead of the MongoDB object id, so it has to be indexable/unique. If it's an update, the createdAt shouldn't change.
UPDATED so it works in the original context, but I prefer the solution I comment with to the correct answer.
I doubt this is supported in the minimongo side of things, but you can always implement the logic on the server and publish the method. But MongoDB supplies a $setOnInsert
operator which has the purpose of only applying that value to the update performed when the "upsert" in fact inserts a new document:
Accounts.upsert(
{ "account_id": obj.account_id },
{
"$setOnInsert": { "created_at": new Date() },
"$set": obj // account_id would be automatically added but it doesn't matter
}
);
Of course presuming that obj
does not already contain aa created_at
field and the data you want is actually a BSON "Date" type rather than an epoch timestamp ( BSON Dates actually store as an epoch timestamp internally anyway ) otherwise convert using .valueOf()
as shown in your example.
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.