Import mongo_dart package stops text from displaying - mongodb

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

Related

How do I save an image into a mongoDB collection using Kmongo?

I searched a lot today but all answers seem to be only in nodejs. I'm currently working on ktor application and I can't seem to find any way to upload images into MongoDB with KMongo.
You can use GridFS to store and retrieve binary files in MongoDB. Here is an example of storing an image, that is requested with the multipart/form-data method, in a test database:
import com.mongodb.client.gridfs.GridFSBuckets
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.litote.kmongo.KMongo
fun main() {
val client = KMongo.createClient()
val database = client.getDatabase("test")
val bucket = GridFSBuckets.create(database, "fs_file")
embeddedServer(Netty, port = 8080) {
routing {
post("/image") {
val multipartData = call.receiveMultipart()
multipartData.forEachPart { part ->
if (part is PartData.FileItem) {
val fileName = part.originalFileName as String
withContext(Dispatchers.IO) {
bucket.uploadFromStream(fileName, part.streamProvider())
}
call.respond(HttpStatusCode.OK)
}
}
}
}
}.start()
}
To make a request run the following curl command: curl -v -F image.jpg=#/path/to/image.jpg http://localhost:8080/image
To inspect stored files run db.fs_file.files.find() in the mongo shell.

Error On Using Route53 ChangeResourceRecordSets

I'm currently using Grails 2.4.5 and used AmazonWebService plugin for grails 2.4.5
I'm trying to create a new recordset on route53 using this plugin.
On my BuildConfig.groovy I used this plugin fro aws web services.
compile ":aws-sdk:1.10.44"
I need your help guys regarding route53 change resource record sets.
I got an error below when I tried to change route53 resource record sets.
Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6). Stacktrace follows:
Message: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6)
This is my code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
AliasTarget target = new AliasTarget('hostedZoneIDHere', 'app.sample.com.')
target.setEvaluateTargetHealth(true)
List<ResourceRecord> resourceRecords = new ArrayList<>()
resourceRecords.add(new ResourceRecord('dNSNameHere'))
ResourceRecordSet recordSet = new ResourceRecordSet('app.sample.com.', RRType.A)
recordSet.setAliasTarget(target)
recordSet.setResourceRecords(resourceRecords)
recordSet.setTrafficPolicyInstanceId('simple')
List<Change> changes = new ArrayList<>()
changes.add(new Change(ChangeAction.CREATE, recordSet))
ChangeBatch changeBatch = new ChangeBatch(changes)
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest('hostedZoneIDHere', changeBatch)
return route53Client.changeResourceRecordSets(request)
}
}
Can you tell me what is the problem with the setup?
I would be glad if you can help me with my problem right now.
Thank you guys.
I already solve this problem. below is the working code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
private static final String DOMAIN_NAME_SERVER = "${System.env.DOMAIN_NAME_SERVER}"
private static final String HOSTED_ZONE_ID = "${System.env.HOSTED_ZONE_ID}"
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
GetHostedZoneResult hostedZoneResult = route53Client.getHostedZone(new GetHostedZoneRequest(HOSTED_ZONE_ID))
HostedZone hostedZone = hostedZoneResult.getHostedZone()
ResourceRecordSet resourceRecordSet = new ResourceRecordSet()
.withName('dNSName')
.withType(RRType.CNAME)
.withTTL(60)
.withResourceRecords([
new ResourceRecord().withValue(DOMAIN_NAME_SERVER)
])
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
.withHostedZoneId(hostedZone.id)
.withChangeBatch(
new ChangeBatch()
.withChanges([
new Change()
.withAction(ChangeAction.CREATE)
.withResourceRecordSet(resourceRecordSet)
])
)
return route53Client.changeResourceRecordSets(request)
}
}

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.

The requested built-in library is not available on Dartium

I am trying to make a very simple application that looks up values in a database by using polymer elements to get input.
My main polymer class looks like this:
library index;
import 'package:polymer/polymer.dart';
import 'lookup.dart';
import 'dart:html';
#CustomTag('auth-input')
class AuthInput extends PolymerElement {
#observable String username = '';
#observable String password = '';
AuthInput.created() : super.created();
void login(Event e, var detail, Node target)
{
int code = (e as KeyboardEvent).keyCode;
switch (code) {
case 13:
{
Database.lookUp(username, password);
break;
}
}
}
}
and a secondary database helper class looks like this:
library database;
import 'package:mongo_dart/mongo_dart.dart';
class Database {
static void lookUp(String username, String password) {
print("Trying to look up username: " + username + " and password: " + password);
DbCollection collection;
Db db = new Db("mongodb://127.0.0.1/main");
db.open();
collection = db.collection("auth_data");
var val = collection.findOne(where.eq("username", username));
print(val);
db.close();
}
}
I keep getting this error and I cannot think of a way around it:
The requested built-in library is not available on Dartium.'package:mongo_dart/mongo_dart.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
The strange thing is, I don't want to use dart:io. The code works fine either running database processes or running polymer processes. I can't get them to work together. I don't see why this implementation of the code will not run.
The first line at https://pub.dartlang.org/packages/mongo_dart says
Server-side driver library for MongoDb implemented in pure Dart.
This means you can't use it in the browser. Your error message indicates the same. The code in the package uses dart:io and therefore can't be used in the browser.
Also mongodb://127.0.0.1/main is not an URL that can be used from within the browser.
You need a server application that does the DB access and provides an HTTP/WebSocket API to your browser client.