我正在尝试为我的Stitch创建一个与我的MongoDB数据库集合的简单连接。在componentDidMount()方法中,我初始化了默认的应用程序客户端,并将其存储在组件的一个变量中。但是,当我试图设置MongoDB遥控器之后,它不能工作,我得到
TypeError: this.client.getServiceClient is not a function. (In 'this.client.getServiceClient(MongoDB.RemoteMongoClient.factory, "mongodb-atlas")', 'this.client.getServiceClient' is undefined)

我已经阅读了所有的这或这等本地文档,并且看到结构不一样,但我不希望用户登录应用程序(为什么我使用AnonymousCredential()),即使我使用这个结构,我也不知道在用户登录后该做什么,如何获取数据?由于没有定义远程客户端,因此没有db和集合。
这是我的组成部分:
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,
},
});有人能帮忙吗?谢谢您:)
发布于 2020-04-13 16:22:07
实际上,从移动应用程序直接连接到远程数据库并不是个好主意。如何使用atlas API或创建一个API与MongoDB通信?
https://stackoverflow.com/questions/61178073
复制相似问题