Meteor + React: Can't get data from mongoDB Collection - mongodb

I have a Meteor Application that I'm developing with React. I still have the autopublish package in my project (autopublish#1.0.7).
Here is my relevant code:
MainMenu.jsx
import React, { Component, PropTypes } from 'react'
import { Meteor } from 'meteor/meteor'
import { FlowRouter } from 'meteor/kadira:flow-router'
import { createContainer } from 'meteor/react-meteor-data'
import { ChatRooms } from '/imports/api/chatrooms.js'
export class MainMenu extends Component {
render() {
console.log(this.props.chatrooms)
return (
{/* Render stuff here is not part of the scope of this question */}
)
}
}
MainMenu.PropTypes = {
chatrooms: PropTypes.array.isRequired
}
export default createContainer(() => {
return {
chatrooms: ChatRooms.find({}).fetch()
}
}, MainMenu)
chatrooms.js
import { Mongo } from 'meteor/mongo'
export const ChatRooms = new Mongo.Collection('chatrooms')
The console.log(this.props.chatrooms) in the MainMenu Component always returns an empty array ([]).
There are definitely items in the Mongo Database because when I run the meteor mongo command in my console and type db.chatrooms.find({}); it returns the 3 items that I've inserted to test this all.
Anyone have any idea what I may be doing wrong here? Help would be much appreciated!

I've figured it out. I left out a crucial step of this whole process.
In my /server/main.js file I needed to add the following line which fixed everything:
import '../imports/api/chatrooms.js

Related

LWC OSS & Jest - Cannot create elements to test as createElement no longer exists

I'm trying to write a unit test for my open source LWC but cannot complete the test as the createElement member from the LWC package no longer exists. I have been following the docs on lwc.dev but they seem to be outdated and still using createElement in their example.
I have a TypeScript-enabled LWR application and I have installed jest, jest-environment-jsdom, #types/jest and #lwc/jest-preset.
Here is my component:
// hello.html
<template>
<h1>Hello, {greeting}!<h1>
<template>
// hello.ts
import { LightningElement } from 'lwc';
export default class Hello extends LightningElement {
greeting = 'World';
}
And here is my unit test:
// __tests__/hello.test.ts
import { createElement } from 'lwc';
import Hello from '../hello';
describe('hello', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders greeting', () => {
const element = createElement('tut-hello', {
is: Hello
});
document.body.appendChild(element);
const div = element.shadowRoot.querySelector('div');
expect(div.textContent).toBe('Hello, World!');
});
});
VS Code is showing me an error line under createElement in my import statement:
Module '"lwc"' has no exported member 'createElement'.ts(2305).
When I run the test I get a failure with the following message:
TypeError: Cannot read properties of null (reading 'textContent').
All LWC examples I could find use createElement yet there are GitHub PRs from years ago with comments saying that createElement api will soon be deprecated.
The only other way I could find to possibly create an element is from a comment in the base LightningComponent class within the framework itself:
customElements.define('tut-hello', Hello.CustomElementConstructor);
const element = document.createElement('tut-hello', {
is: 'tut-hello'
});
But this doesn't work for me either. How do I create an element for testing with the latest version of LWC OSS?

I can't access an object's properties

The next lines work fine and I can see the whole object in the console log:
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject)
In the console, I can see the oneProject's properties, even the name property.
Now with the following lines, the result is an error:
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)
The error is: "Cannot read property 'name' of undefined".
This is the whole code:
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Projects } from '/imports/api/projects.js';
import ProjectFormUpdate from './ProjectFormUpdate.jsx';
export default ProjectFormUpdateContainer = withTracker(({ key1 }) => {
Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)
return {
oneProject:oneProject,
};
})(ProjectFormUpdate);
A subscription in Meteor is asynchronous. This means the data is not always immediately available.
Tracker.autorun(() => {
const sub = Meteor.subscribe('projects');
if (sub.ready()){
const oneProject = Projects.findOne(key1);
console.log(oneProject.name);
}
});
will not try to find the project until the subscription is ready.

undefined is not a function (evaluating '_reactNativeMeteor2.default.collection("messages").find().fetch()')

In my Meteor app I have a collection definition like this:
this.collections.Messages = new Mongo.Collection("messages");
Now I try to connect to it from a react native meteor like this:
import React, { Component } from 'react';
import Meteor, { createContainer } from 'react-native-meteor';
import MessageListComponent from '../routes/messageList';
export default MessageListContainer = createContainer(() => {
const messagesHandle = Meteor.subscribe('userMessage');
const loading = !messagesHandle.ready();
const messages = Meteor.collection("messages").find().fetch();
return {
loading,
messages
};
}, MessageListComponent);
But it's return below red error message on device:
undefined is not a function (evaluating '_reactNativeMeteor2.default.collection("messages").find().fetch()')
What is the problem guys?
Try eliminating the fetch() from your messages const:
const messages = Meteor.collection('messages').find();
The fetch converts the cursor into an array, and probably isn't necessary here. Also, this line is the only one where you have double quotes, but I'm not sure that that is relevant.

How to properly subscribe to collection on Meteor client side?

First of all, I'm not a newbie to Meteor, but after the latest Meteor updates I have to re-study the framework, and now I'm having trouble using Meteor subscription on the client side.
To be specific, I have subscribed a collection on the client side, however when I try to refer to it the browser console reported the error:
Exception in template helper: ReferenceError: Chatbox is not defined
Here's the structure of my code:
imports/api/chatbox/chatboxes.js
// define the collection
export const Chatbox = new Mongo.Collection("chatbox");
imports/api/chatbox/server/publication.js - to be imported in server/main.js
import { Meteor } from "meteor/meteor";
import { Chatbox } from "../chatboxes";
Meteor.publish("chatbox", function(parameter) {
return Chatbox.find(parameter.find, parameter.options);
});
imports/ui/chatbox/chatbox.js - page template to be rendered as content upon routing
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import './chatbox.html';
import './chatbox.css';
Template.chatbox.onCreated(function bodyOnCreated() {
this.state = new ReactiveDict();
// create subscription query
var parameters = {
find: {
// query selectors
permission: "1001",
},
options: {
// query options
}
};
Meteor.subscribe("chatbox", parameters);
});
Template.chatbox.helpers({
canAddMore() {
// Chatbox collection direct access from client
return Chatbox.find().count() < 3;
},
});
I'd appreciate if you can help me with this issue. Thanks all for taking your time reading my question!
Regards
You need to import Chatbox in imports/ui/chatbox/chatbox.js:
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import { Chatbox } from "../chatboxes"; // correct this path
It's undefined right now because it hasn't been imported.

Import mongo_dart package stops text from displaying

The following code works just fine...simply displaying some JSON in an unordered list:
import 'dart:html';
import 'dart:convert';
main() {
// Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
void reverseText(MouseEvent event) {
var text = querySelector("#sample_text_id").text;
var buffer = new StringBuffer();
for (int i = text.length - 1; i >= 0; i--) {
buffer.write(text[i]);
}
querySelector("#sample_text_id").text = buffer.toString();
}
void showJSON(MouseEvent event) {
var path = 'hcps.json';
var hcpDisplay = querySelector('#json_length_id');
HttpRequest.getString(path).then((String fileContents) {
List<String> hcpList = JSON.decode(fileContents);
for (int i = 0; i < hcpList.length; i++) {
hcpDisplay.children.add(new LIElement()..text = hcpList[i].toString());
}
});
}
However, when I add an import statement for mongo-dart, the JSON is not displayed, though I do not receive an error:
import 'dart:html';
import 'dart:convert';
import 'package:mongo_dart/mongo_dart.dart';
main() {
Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
...
The mongo_dart package has been added to pubspec.yaml as a dependency.
Does anyone have an idea as to why importing the mongo_dart package would cause the json text not to display, though there is no error? Thank you in advance.
As stated in package readme
mongo-dart is a server-side driver library for MongoDb implemented in
pure Dart
.
It cannot work at client side. Main reason for that - browsers do not have real sockets to connect to databases like mongodb, mysql, postgress and so on. You may look at some database with a RESTful API like CouchDB. Or you should use some middleware - for example objectory.
You could try
import 'package:mongo_dart/mongo_dart.dart' as mdb;
main() {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
to see if there is a conflict
You could also add a try/catch block
try {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
} catch(e) {
print(e)
}
sometimes exceptions are swallowed due to the use of zones (might not help here though) but I think it's worth a try.
It is possible that the package cache directory is corrupted.
You could try
pub cache repair