0

This might be a simple javascript question. I finally got this meteor upsert statement working, except in the cases where a matching record does not already exist. It works if I replace chan._id with '' or null, so what I want to do is simply use null in place of chan._id in the cases where chan finds no existing record. I just don't know how to write such a thing.

//client
var chfield = t.find('#today-channel').value,
chan = Today.findOne({channel: chfield})

Meteor.call('todayUpsert', chan._id, {
    channel: chfield,
    admin: Meteor.userId(),
    date: new Date(),
});


//client and server
Meteor.methods({
  todayUpsert: function(id, doc){
     Today.upsert(id, doc);
  }
});
Quin
  • 441
  • 5
  • 12

2 Answers2

0

When you're working with an upsert, you won't know the _id unless the entry already exists. In this case if you search for the db entry with the document rather than the _id, you should get what you need.

//client

var chfield = t.find('#today-channel').value;


Meteor.call('todayUpsert', {
    channel: chfield,
    admin: Meteor.userId(),
    date: new Date(),
});


//client and server
Meteor.methods({
    todayUpsert: function(doc){
        // upsert the document -- selecting only on 'channel' and 'admin' fields.
        Today.upsert(_.omit(doc, 'date'), doc);
    }
});
hharnisc
  • 937
  • 7
  • 11
  • But because you removed the selector, its only use becomes to insert new documents. How would you modify this so that if a document exists, it will update, and if doesn't, it will create a new one? – Quin Feb 28 '14 at 17:17
  • Its always inserting because the date is going to be different each time you call the function. I'll edit the code above. – hharnisc Feb 28 '14 at 17:37
0

I found what I was looking for.

var chfield = t.find('#today-channel').value,

Meteor.call('todayUpsert',
    Today.findOne({channel: chfield}, function(err, result){
        if (result) {
            return result._id;
        }
        if (!result) {
            return null;
        }
    }),
    {
        channel: chfield,
        admin: Meteor.userId(),
        date: new Date()
    }
);
Quin
  • 441
  • 5
  • 12