Meteor.publish("Sessions", (sessionId) => { check(sessionId, Match.OneOf(String, null)); const created = new Date().getTime(); let newSessionId; // if we don"t have a sessionId create a new session // REALLY - we should always have a client sessionId if (!sessionId) { newSessionId = ServerSessions.insert({ created }); } else { newSessionId = sessionId; } // get the session from existing sessionId const serverSession = ServerSessions.find(newSessionId); // if not found, also create a new server session if (serverSession.count() === 0) { ServerSessions.insert({ _id: newSessionId, created }); } // set global sessionId Reaction.sessionId = newSessionId; // return cursor return ServerSessions.find(newSessionId); });
Tasks.initSampleData = function() { Tasks.remove({}); Tasks.insert({name: "Testtask 1"}); Tasks.insert({name: "Testtask 2"}); Tasks.insert({name: "Testtask 3"}); Tasks.insert({name: "Testtask 4"}); }
Tinytest.addAsync('Relations - observe', function (test, done) { var quotesName = Random.id(), quotes = new Mongo.Collection(quotesName), products = new Mongo.Collection(Random.id()), publish = Random.id(), names = data.names, docs = data.quotes; for (var doc in docs) { var quote = docs[doc]; quotes.insert(quote); for (var i = 0; i < 3; i ++) { products.insert({ quoteId: quote._id, name: names[i], price: 1000 * i }); } }; PublishRelations(publish, function () { this.cursor(quotes.find(), function (id, doc) { var productsCursor = products.find({quoteId: id}); this.observe(productsCursor, { added: function (doc) { test.equal(doc.name, names[doc.price / 1000]); } }); this.observeChanges(productsCursor, { added: function (prodId, doc) { test.equal(doc.name, names[doc.price / 1000]); } }); }); }); var client = Client(); client._livedata_data = function (msg) { if (msg.msg == 'added') { test.equal(msg.collection, quotesName); } else if (msg.msg == 'ready') { client.disconnect(); done(); } }; client.subscribe(publish); });
Tinytest.addAsync('Relations - changeParentDoc', function (test, done) { var quotesName = Random.id(), quotes = new Mongo.Collection(quotesName), users = new Mongo.Collection(Random.id()), publish = Random.id(), docs = data.quotes; for (var doc in docs) { var quote = docs[doc]; quotes.insert(quote); users.insert({ _id: quote.user, profile: { age: quote._id * 2 + 15, postalCode: quote._id * 99 } }); }; PublishRelations(publish, function () { this.cursor(quotes.find(), function (id, doc) { var user = this.changeParentDoc(users.find({_id: doc.user}), function (id, doc) { return {userProfile: doc.profile}; }); doc.userProfile = user.userProfile; }); }); var client = Client(); client._livedata_data = function (msg) { if (msg.msg == 'added') { test.equal(msg.collection, quotesName); var user = users.findOne({_id: msg.fields.user}); users.update({_id: user._id}, {$set: {'profile.age': user.profile.age + 1}}); test.equal(msg.fields.userProfile, user.profile); } else if (msg.msg == 'changed') { test.equal(msg.collection, quotesName); test.equal(msg.fields.userProfile.age, msg.id * 2 + 16); } else if (msg.msg == 'ready') { client.disconnect(); done(); } }; client.subscribe(publish); });
it('should stub non-registered one-off collections', function () { expect(widgets.find().count()).to.equal(1); StubCollections.stub([widgets]); expect(widgets.find().count()).to.equal(0); widgets.insert({}); widgets.insert({}); expect(widgets.find().count()).to.equal(2); StubCollections.restore(); expect(widgets.find().count()).to.equal(1); });
blockInsert: function(estimationId, parentId, index) { Blocks.find({ parentId: parentId }).forEach(function(element) { if (element.index >= index) { Blocks.update({ _id: element._id }, { $set: { index: element.index + 1 } }); } }); var newBlock = { userId: Meteor.userId(), value: "", isParent: false, estimationId: estimationId, parentId: parentId, hours: "0", rate: 0.0, index: index }; Blocks.insert(newBlock); Meteor.call('estimationUpdate', estimationId, { dateUpdated: new Date() }); },
it('no errors when using a schemaless collection', function (done) { const noSchemaCollection = new Mongo.Collection('noSchema', { transform(doc) { doc.userFoo = 'userBar'; return doc; }, }); noSchemaCollection.insert({ a: 1, b: 2 }, (error, newId) => { expect(!!error).toBe(false); expect(!!newId).toBe(true); const doc = noSchemaCollection.findOne(newId); expect(doc instanceof Object).toBe(true); expect(doc.userFoo).toBe('userBar'); noSchemaCollection.update({ _id: newId }, { $set: { a: 3, b: 4 } }, error => { expect(!!error).toBe(false); done(); }); }); });
it('extending a schema with a selector after attaching it, collection2 validation respects the extension', (done) => { const schema = new SimpleSchema({ foo: String }); const collection = new Mongo.Collection('ExtendAfterAttach2'); collection.attachSchema(schema, { selector: { foo: "foo" } }); collection.insert({ foo: "foo", bar: "bar" }, { filter: false }, (error) => { expect(error.invalidKeys[0].name).toBe('bar'); schema.extend({ bar: String }); collection.insert({ foo: "foo", bar: "bar" }, { filter: false }, (error2) => { expect(!!error2).toBe(false); done(); }); }); });
_.times(3, (i) => { const todo = Factory.build('todo', { listId: list._id, createdAt: new Date(timestamp - (3 - i)), }); todosCollection.insert(todo); });
'data_db.insert': function(obj){ // this.unblock(); check(obj, Object); console.log( "+++++++ inserting ++++++++" ); console.log( obj ); if ( obj.data ){ obj.data = JSON.parse(obj.data); for( d in obj.data ){ // we should probably check to make sure we need to parse here obj.data[d] = parseFloat(obj.data[d]); } } if (obj.published_at){ console.log(obj.published_at); obj.published_at = new Date(obj.published_at); console.log(obj.published_at); } // if( ! Meteor.userId() ){ // throw new Meteor.Error('not-authorized'); // } DATA_DB.insert( obj, function( err, res ){ if ( err ) throw err; if ( res ){ console.log("== SUCCESS! =="); console.log(res); } }); },
export const createProfile = (userId, options) => { const {city, state, zipcode} = data; const {address, screenName, fullName} = options; options.avatar = ''; options.emailVisible = false; options.offerNotify = false; options.requestNotify = false; options.offerNotifySMS = false; options.requestNotifySMS = false; options.phone = ''; validateProfile(userId, options); Profiles.insert({ userId, screenName, fullName, address, city, state, zipcode, avatar: options.avatar, phone: options.phone, emailVisible: options.emailVisible, offerNotify: options.offerNotify, requestNotify: options.requestNotify, offerNotifySMS: options.offerNotifySMS, requestNotifySMS: options.requestNotifySMS }) }
'Decks.add': function(board_id) { check(deck_id, String); return Decks.insert({ title: 'New deck...', dashboardId: board_id }); }
_.times(3, i => { const element = Factory.build('element', { circuitId: circuit._id, createdAt: new Date(timestamp - (3 - i)), }); elementsCollection.insert(element); });
Tinytest.addAsync('Relations - cursor basic', function (test, done) { var quotesName = Random.id(), productsName = Random.id(), quotes = new Mongo.Collection(quotesName), products = new Mongo.Collection(productsName), names = data.names, publish = Random.id(), docs = data.quotes; for (var doc in docs) { var quote = docs[doc]; quotes.insert(quote); for (var i = 0; i < 3; i ++) { products.insert({ quoteId: quote._id, name: names[i], price: 1000 * i }); } }; PublishRelations(publish, function () { this.cursor(quotes.find(), function (id, doc) { this.cursor(products.find({quoteId: id})); }); }); var client = Client(); client._livedata_data = function (msg) { if (msg.collection == productsName) { var fields = msg.fields; test.isTrue(quotes.findOne({_id: fields.quoteId})); test.equal(fields.name, names[fields.price / 1000]); } else if (msg.collection == quotesName) { test.equal(msg.fields, quotes.findOne({_id: msg.id}, {fields: {_id: 0}})); } else if (msg.msg == 'ready') { client.disconnect(); done(); } }; client.subscribe(publish); });
it('for client insert, autoValues should be added on the server only (added to only a validated clone of the doc on client)', function (done) { collection.insert({}, (error, id) => { const doc = collection.findOne(id); expect(doc.clientAV).toBe(undefined); expect(doc.serverAV).toBe(1); done(); }); });
it('runs function once for LocalCollection', function (done) { localCollection.insert({}, (error, id) => { const doc = localCollection.findOne(id); expect(doc.clientAV).toBe(1); expect(doc.serverAV).toBe(undefined); done(); }); });
it('with getAutoValues false, does not run function for LocalCollection', function (done) { localCollection.insert({}, { getAutoValues: false }, (error, id) => { const doc = localCollection.findOne(id); expect(doc.clientAV).toBe(undefined); expect(doc.serverAV).toBe(undefined); done(); }); });
export const createCommentNotification = function (comment) { Notifications.insert({ userId: comment.userId, postId: comment.postId, commentId: comment._id, commenterName: comment.author, read: false }); };
'songs.insert':function(track){ let s = Songs.findOne({"track.id":track.id}); if(!s){ Songs.insert({ track:track, addedOn : new Date() }); } },
Meteor.publish('conversation_from_cluster', function getConversation(clusterId) { var ndocs = Conversations.find({'cluster_id': clusterId}).fetch().length; if (ndocs == 0) { var user = Meteor.users.findOne(this.userId); Conversations.insert({'cluster_id': clusterId, 'user_id': this.userId, 'username': user.username, 'state': 'uninitialized', 'history': []}); } return Conversations.find({'cluster_id': clusterId}); });
function insertMess(mess) { Messages.insert({ text: mess, createdAt: new Date(), // current time owner: Meteor.userId, username: Meteor.user().username, }); }
it('empty strings are removed but we can override', function (done) { const RESSchema = new SimpleSchema({ foo: { type: String }, bar: { type: String, optional: true } }); const RES = new Mongo.Collection('RES'); RES.attachSchema(RESSchema); // Remove empty strings (default) RES.insert({ foo: "foo", bar: "" }, (error, newId1) => { expect(!!error).toBe(false); expect(typeof newId1).toBe('string'); const doc = RES.findOne(newId1); expect(doc instanceof Object).toBe(true); expect(doc.bar).toBe(undefined); // Don't remove empty strings RES.insert({ foo: "foo", bar: "" }, { removeEmptyStrings: false }, (error, newId2) => { expect(!!error).toBe(false); expect(typeof newId2).toBe('string'); const doc = RES.findOne(newId2); expect(doc instanceof Object).toBe(true); expect(doc.bar).toBe(''); // Don't remove empty strings for an update either RES.update({ _id: newId1 }, { $set: { bar: '' } }, { removeEmptyStrings: false }, (error, result) => { expect(!!error).toBe(false); expect(result).toBe(1); const doc = RES.findOne(newId1); expect(doc instanceof Object).toBe(true); expect(doc.bar).toBe(''); done(); }); }); }); });
"tote.FashionItem.addItem": function(url, category) { //if (!Meteor.userId()) { // throw new Meteor.Error('unauthorized'); // } let newItem = {}; newItem.userId = Meteor.userId(); newItem.itemUrl = url; newItem.category = category; newItem._id = FashionItemCollection.insert(newItem); },
contact : function (name,email,companyname,contactnumber,comment) { contact.insert({ name : name, email : email, companyname : companyname, contactnumber : contactnumber, comment : comment, createdAt : new Date() }); },
_save(toClient){ if (this._shouldSave){ let r = this._record r.returnedToClient = toClient; r.savedAt = new Date(); r.lifetime = r.savedAt - r.createdAt; Records.insert(r); } return toClient; }
'cars.insert': function (data){ //var currentUser = Meteor.userId(); check(data.make,String); check(data.model,String); check(data.year,Number); check(data.description,String); //check(data.url,String); return Cars.insert(data); },
'questions.create': function(text) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } Questions.insert({ text, userId: this.userId, createdAt: new Date(), // current time }); },
Roles.createRole = role => { role = role.trim().toLowerCase(); try { if (!rolesDb.findOne({name: role})) { return rolesDb.insert({name: role}); } } catch (e) { throw new Error("Roles: problem inserting role. " + e); } };
'product.insert': function() { return Products.insert({ sku: '', name: '', image: 'http://dummyimage.com/600x400', summary: '', description: '', price: '', createdAt: new Date(), ownerId: this.userId }) },
students.forEach(function(student) { // if this is a new student, create a record for them var currentRecord = OrderedChoices.findOne({email: student.email}); if (!currentRecord) { OrderedChoices.insert({email: student.email, choices: {}, yearsSubmitted: []}) } // add this year's choices to the student record OrderedChoices.update( {email: student.email}, {$set: {['choices.' + currentYear]: allChoices[student.grade]}}, ); });