Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应本机-MongoDB同步故障_Reactjs_Mongodb_React Native_Realm_React Native Ios - Fatal编程技术网

Reactjs 反应本机-MongoDB同步故障

Reactjs 反应本机-MongoDB同步故障,reactjs,mongodb,react-native,realm,react-native-ios,Reactjs,Mongodb,React Native,Realm,React Native Ios,我是MongoDB/React Native新手,我正试图打开一个领域,使用TaskProvider查看我的所有任务,如教程()所示。我对它做了一些修改,以便它使用用户打开一个领域,分区键是用户的电子邮件。我不知道为什么我总是会遇到这样的错误:“非法领域路径(绑定)”}。下面,我附加了我修改过的TaskProvider.js。我想让它与我的MongoDB领域同步,但我在这里遇到了麻烦 编辑:我添加了我的页面 在同步设置中,您将分区键命名为“name”,但在代码中,您将user.email用作分区

我是MongoDB/React Native新手,我正试图打开一个领域,使用TaskProvider查看我的所有任务,如教程()所示。我对它做了一些修改,以便它使用用户打开一个领域,分区键是用户的电子邮件。我不知道为什么我总是会遇到这样的错误:“非法领域路径(绑定)”}。下面,我附加了我修改过的TaskProvider.js。我想让它与我的MongoDB领域同步,但我在这里遇到了麻烦

编辑:我添加了我的页面


在同步设置中,您将分区键命名为“name”,但在代码中,您将user.email用作分区值。还可以尝试从构造函数和模式中删除分区字段。Realm将自动使用字段“name”进行分区,因为这是您在同步页面上指定的字段。

在同步设置中,您将分区键命名为“name”,但在代码中,您将user.email用作分区值。还可以尝试从构造函数和模式中删除分区字段。Realm将自动使用字段“name”进行分区,因为这是您在同步页面上指定的字段

import React, {useContext, useState, useEffect, useRef} from 'react';
import Realm from 'realm';
import {useAuth} from './AuthProvider';
import {Task} from './schemas';

// Create the context that will be provided to descendants of TasksProvider via
// the useTasks hook.
const TasksContext = React.createContext(null);

const TasksProvider = ({ children }) => {


  // Get the user from the AuthProvider context.
  const {user} = useAuth();

  // The tasks list will contain the tasks in the realm when opened.
  const [tasks, setTasks] = useState([]);

  // This realm does not need to be a state variable, because we don't re-render
  // on changing the realm.
  const realmRef = useRef(null);

  // The effect hook replaces lifecycle methods such as componentDidMount. In
  // this effect hook, we open the realm that contains the tasks and fetch a
  // collection of tasks.
  useEffect(() => {
    // Check that the user is logged in. You must authenticate to open a synced
    // realm.
    if (user == null) {
      console.warn('TasksView must be authenticated!');
      return;
    }

    // Define the configuration for the realm to use the Task schema. Base the
    // sync configuration on the user settings and use the project ID as the
    // partition value. This will open a realm that contains all objects where
    // object._partition == projectId.

    const _partitionKey = user.email;

    const config = {
      schema: [Task.schema],
      sync: {
        user: user,
        partitionValue: _partitionKey,
      },
    };

    console.log(
      `Attempting to open Realm for user ${
        user.identity
      } with config: ${JSON.stringify(config)}...`,
    );

    // Set this flag to true if the cleanup handler runs before the realm open
    // success handler, e.g. because the component unmounted.
    let canceled = false;

    // Now open the realm asynchronously with the given configuration.
    Realm.open(config)
      .then((openedRealm) => {
        // If this request has been canceled, we should close the realm.
        if (canceled) {
          openedRealm.close();
          return;
        }

        // Update the realmRef so we can use this opened realm for writing.
        realmRef.current = openedRealm;

        // Read the collection of all Tasks in the realm. Again, thanks to our
        // configuration above, the realm only contains tasks where
        // task._partition == projectId.
        const syncTasks = openedRealm.objects('Task');

        // Watch for changes to the tasks collection.
        openedRealm.addListener('change', () => {
          // On change, update the tasks state variable and re-render.
          setTasks([...syncTasks]);
        });

        // Set the tasks state variable and re-render.
        setTasks([...syncTasks]);
      })
      .catch((error) => console.warn('Failed to open realm:', error));

    // Return the cleanup function to be called when the component is unmounted.
    return () => {
      // Update the canceled flag shared between both this callback and the
      // realm open success callback above in case this runs first.
      canceled = true;

      // If there is an open realm, we must close it.
      const realm = realmRef.current;
      if (realm != null) {
        realm.removeAllListeners();
        realm.close();
        realmRef.current = null;
      }
    };
  }, [user, user.email]); // Declare dependencies list in the second parameter to useEffect().

  // Define our create, update, and delete functions that users of the
  // useTasks() hook can call.
  const createTask = (newTaskName, newPostDescription) => {
    const realm = realmRef.current;
    // Open a write transaction.

    realm.write(() => {

      // Create a new task in the same partition -- that is, in the same project.

      realm.create(

        'Task',

        new Task({name: newTaskName || 'New Task', description: newPostDescription, partition: user.email}),

      );

    });

  };

  // Define the function for updating a task's status.
  const setTaskStatus = (task, status) => {
    // One advantage of centralizing the realm functionality in this provider is
    // that we can check to make sure a valid status was passed in here.
    if (
      ![
        Task.STATUS_OPEN,
        Task.STATUS_IN_PROGRESS,
        Task.STATUS_COMPLETE,
      ].includes(status)
    ) {
      throw new Error(`Invalid Status ${status}`);
    }
    const realm = realmRef.current;


    realm.write(() => {

      task.status = status;

    });

  };

  // Define the function for deleting a task.
  const deleteTask = (task) => {
    const realm = realmRef.current;

    realm.write(() => {

      realm.delete(task);

    });

  };


  // Render the children within the TaskContext's provider. The value contains
  // everything that should be made available to descendants that use the
  // useTasks hook.
  return (
    <TasksContext.Provider

      value={{

        createTask,

        deleteTask,

        setTaskStatus,

        tasks,
      }}>

      {children}
    </TasksContext.Provider>
  );
};

// The useTasks hook can be used by any descendant of the TasksProvider. It
// provides the tasks of the TasksProvider's project and various functions to
// create, update, and delete the tasks in that project.
const useTasks = () => {
  const value = useContext(TasksContext);
  if (value == null) {
    throw new Error('useTasks() called outside of a TasksProvider?');
  }
  return value;
};

export {TasksProvider, useTasks};

import {ObjectId} from 'bson';

class Task {
  constructor({
    name,
    description,
    status = Task.STATUS_OPEN,
    id = new ObjectId(),
    partition,
    date_published = Date()
  }) {
    this._id = id;
    this.name = name;
    this.status = status;
    this.description = description;
    this._partition = partition;
    this.date_published = date_published
  }

  static STATUS_OPEN = 'Open';
  static STATUS_IN_PROGRESS = 'InProgress';
  static STATUS_COMPLETE = 'Complete';

  static schema = {
    name: 'Task',
    properties: {
      _id: 'objectId',
      _partition: 'string',
      assignee: 'objectId',
      date_published: 'date',
      name: 'string',
      status: 'string'
    },
    primaryKey: '_id',
  };
}

export {Task};