简体   繁体   中英

Unable to create Documents collection in meteor

Trying to create a collection called "documents" and insert a document from main.js in my meteor application. When trying to execute the findOne method in the console window I get "Uncaught ReferenceError: Documents is not defined". I am using meteor version 1.10.2. I have mongo installed on my computer and its mongo shell version is 4.2.1. How do I enable my app to use mongo?

main.js

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

Meteor.startup(() => {
  // code to run on server at startup

  this.Documents = new Mongo.Collection("documents");

  if(!Documents.findOne()) {
    Documents.insert({title:"my new documents"});
  }

});

Documents is not defined because you assigned the collection to this.documents Just define Documents like a normal variable

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

const Documents = new Mongo.Collection("documents");

if(!Documents.findOne()) {
  Documents.insert({title:"my new documents"});
}

export { Documents }

To access Documents in the console, you need to import the module into the console (like you would in a file), except in the console, you do this with require :

require('/path/to/main').Documents

Note: this is only possible when Documents is exported

Alternatively, you can make it global by assigning it to window or global :

const Documents = new Mongo.Collection("documents");
window.Documents = Documents;

With globals you just need to be careful not to name other variables with the same name so you know what object you're handing

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