我想使用 Realm 通过网站写入我的 MongoDB 数据库。我已经使用独立的 TypeScript 文件测试了我的代码,该文件导入领域如下:
let {Realm} = require('realm');
现在,我正在尝试将其集成到我的网站中,并在我的“db.ts”文件中包含以下内容
import Realm from 'realm';
interface MongoDBDocument {
[key: string]: any;
}
export async function writeToMongoDB(document: MongoDBDocument, collectionName: string): Promise<any> {
const app = new Realm.App({ id: <MY_ID> });
const credentials = Realm.Credentials.anonymous();
try {
const user = await app.logIn(credentials);
const mongo = user.mongoClient("mongodb-atlas");
const collection = mongo.db("txinfo").collection(collectionName);
const res = await collection.insertOne(document);
return res;
} catch (err) {
console.error("Failed:", err);
throw err; // Rethrow the error to handle it in the calling function
}
}
但是,当我运行
pnpm build
时,我收到错误:
Package path . is not exported from package <LOCAL_PATH>/node_modules/realm
。 我是这一切的新手,但是看看 *<LOCAL_PATH/node_modules/realm/package.json
,我在导出中看到以下内容:
"exports": {
".": {
"types": "./dist/public-types/index.d.ts",
"node": "./dist/platform/node/index.js",
"react-native": "./index.react-native.js"
},
"./experimental/base-url": {
"types": "./dist/public-types/experimental/base-url.d.ts",
"default": "./dist/experimental/base-url.js"
},
"./scripts/submit-analytics": "./scripts/submit-analytics.mjs",
"./react-native.config.js": "./react-native.config.js",
"./package.json": "./package.json"
},
好像有一个“。”出口。 有人可以帮我弄清楚如何正确导入领域吗? 我也尝试过
import {Realm} from '@realm/react'
,但同样的错误
我的项目的 package.json 看起来像这样:
"dependencies": {
"next": "14.2.3",
"postcss-loader": "^8.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.0",
"realm": "^12.9.0",
...
},
将导入更新为:
import * as Realm from "realm-web";
解决了问题。