Domanda

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);
  }
});
È stato utile?

Soluzione 2

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()
    }
);

Altri suggerimenti

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);
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top