I am trying to create a simple connection to my MongoDB database collection for my Stitch App. In the componentDidMount()
method I initialize the default app client and store it in a variable of the component. But when I try to set the MongoDB remote after, it doesn't work, I get the
TypeError: this.client.getServiceClient is not a function. (In 'this.client.getServiceClient(MongoDB.RemoteMongoClient.factory, "mongodb-atlas")', 'this.client.getServiceClient' is undefined)
I have read all React Native docs such as this or this and see the structure isn't the same but I don't want the user to log in on the app (why I used the AnonymousCredential()
) and even if I were to use this structure, I wouldn't know what to do once the user is logged in, how to get the data? Since there is no Remote Client defined, therefore no db and no collection.
Here is my component:
import React from "react";
import { StyleSheet, View, TextInput, Button, FlatList } from "react-native";
import PlayerItem from "./PlayerItem";
import { Stitch, AnonymousCredential } from "mongodb-stitch-react-native-sdk";
const MongoDB = require("mongodb-stitch-react-native-services-mongodb-remote");
export default class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
players: [],
};
this.query = "";
}
componentDidMount() {
this.client = Stitch.initializeDefaultAppClient("kungfuzone-rzksu");
const mongodb = this.client.getServiceClient(
MongoDB.RemoteMongoClient.factory,
"mongodb-atlas"
);
this.db = mongodb.db("players");
this._displayPlayersOnLoad();
}
_displayPlayersOnLoad() {
this.client.auth
.loginWithCredential(new AnonymousCredential())
.then(this._displayPlayers)
.catch(console.error);
}
_displayPlayers() {
this.db
.collection("kungfuzone")
.find({}, { limit: 1000 })
.asArray()
.then((players) => {
this.setState({ players: players });
});
}
_updateQuery(text) {
this.query = text;
}
_searchPlayers(query) {
if (query.length > 0) {
this.stitchClient.auth
.loginWithCredential(new AnonymousCredential())
.then(() => this.setState({ players: db.find({ name: query }).asArray() }))
.catch(console.error);
}
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.textinput}
onChangeText={(input) => this._updateQuery(input)}
placeholder="Player's name"
/>
<Button title="Search" onPress={() => this._searchPlayers(this.query)} />
<FlatList
data={this.state.players}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => <PlayerItem player={item} />}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
},
textinput: {
marginLeft: 5,
marginRight: 5,
height: 50,
borderColor: "#000000",
borderWidth: 1,
paddingLeft: 5,
},
});
Can anyone help? Thank you :)