简体   繁体   中英

Meteor: insert only working on client, not persisting in server side database

I am trying to insert a document into an Activities collection every time a user executes an action. Here is how I set it up:

Here is my createActivity Meteor.method within collections/activities.coffee :

@Activities = new Mongo.Collection('activities')

Activities.allow
  insert: (userId, activity) ->
    activity.userId == userId

Meteor.methods
  createActivity: (movieId, userId) ->
    # if Meteor.isServer
    #   timer = Stats.createTimer("methods.createActivity")
    Activities.insert {
      docId: movieId
      userId: userId
      action: "favorite"
      collection: "movies"
      createdAt: new Date
    }, (error, results) ->
      console.log error, results
    return

Here is where it gets called, in another collection-- collections/lists.coffee . It is getting called within another Meteor.method which gets called on a click event

Meteor.methods
  toggleFavorited: (movieId) ->
    if Meteor.isServer
      timer = Stats.createTimer("methods.toggleFavorited")
    user = Meteor.user()
    return unless user?
    favorited = Meteor.call('toggleInList', user.favorites, movieId)
    if favorited
      Meteor.call 'createActivity', movieId, Meteor.userId()  #LOOK HERE !!!!!
      Movies.update({mid: movieId}, {$inc: favorites: 1})

    else
      Movies.update({mid: movieId}, {$inc: favorites: -1})
    if Meteor.isServer
      timer.stop()
    favorited

Here is my publication and subscription: server/publications.coffee

Meteor.publish 'activities', ->
  return Activities.find()

lib/router.coffee

Router.configure
  layoutTemplate: 'layout'
  loadingTemplate: 'loading'
  notFoundTemplate: 'notFound'
  trackPageView: true
  waitOn: ->
    [
      Meteor.subscribe("activities")
    ]

Here is the console log from when I do the user action that triggers the Activties insert method: 在此处输入图片说明

But the document isn't persisted in the database! Why is that?

Thanks for your help

Are you able to share your folder structure, potentially your method is defined somewhere that meteor thinks is only client-specific code which may explain why it is not getting executed on the server.

My project has the following folders:

/client/
/both <-- accessible to both client & server
/server <-- looks like you have this, server only code.

If you don't, maybe try moving the method code to a /both/lib folder and see if it gets run on the server.

How did you define your collection? Did you by any chance pass null as the argument?

Activities = new Mongo.Collection(null)

will create a local Collection which is not persisted

Activities = new Mongo.Collection("activities")

will be persisted on the server

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM