Search code examples
javascriptnode.jsreactjsmongodbmeteor

How can I insert data to my collection on my server-side main.js with meteor?


I am new with the meteor trying to modify the tutorial codes, I have a code listening packets on my server-side main.js. I also need to insert the data printed on the console to my database collection.

import { Meteor } from 'meteor/meteor';
import '/imports/api/tasks';
import { createServer } from "net";
import { Tasks } from "../imports/api/tasks"

Meteor.startup(() => {

  const server = createServer(socket => {
    socket.write("SEND OK")
    socket.on("data", data => {
      const text = data.toString();
      console.log(text);
    })
  })

  server.listen(8080)

});

Here is the code for my database in my imports/API folder. I couldn't manage to insert with the meteor methods. What is the proper way to do it?

import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

export const Tasks = new Mongo.Collection('tasks');

Meteor.methods({
  'tasks.insert'(text) {
    check(text, String);

    Tasks.insert({
      text,
      createdAt: new Date,
      owner: this.userId,
      username: Meteor.users.findOne(this.userId).username
    })
  },

  'tasks.remove'(taskId) {
    check(taskId, String);

    const task = Tasks.findOne(taskId);

    Tasks.remove(taskId);
  },

});

if (Meteor.isServer) {
  Meteor.publish('tasks', function() {
    return Tasks.find({
      
    });
  })
}

Solution

  • Your method definition looks good and should work (including the insertion into the collection). But you don't need a method to do server-side functions. Since your socket server seems to run on the server as well (as it should), you can just insert into the collection directly from there. For instance:

      const server = createServer(Meteor.bindEnvironment(socket => {
        socket.write("SEND OK")
        socket.on("data", Meteor.bindEnvironment(data => {
          const text = data.toString();
          console.log(text);
          Tasks.insert({
            text,
            createdAt: new Date
          })
        }))
      }))
    

    Of course, since that is running on the server, there is no concept of "current user" for these insertions. How do you know for whom the received data is? Is that part of the data coming on the socket? Once you know that you can add code to add that as owner and username as you had in your method definition, which is the schema I assume you want.


    PS: updated based on error mentioned in the comments