skip to Main Content

I took the code from the documentation, but it doesn’t work.

pub fn get_countries(&self) {
  let cursor = self.countries.find(None, None);
  for doc in cursor {
    println!("{}", doc?)
  }
}

mongodb::sync::Cursor<bson::Document> doesn't implement std::fmt::Display

mongodb::sync::Cursor<bson::Document> cannot be formatted with the default formatter

the ? operator can only be applied to values that implement std::ops::Try

the ? operator cannot be applied to type mongodb::sync::Cursor<bson::Document>

Also the cursor.collect() does not work correctly.

the method collect exists for enum std::result::Result<mongodb::sync::Cursor<bson::Document>, mongodb::error::Error>, but its trait bounds were not satisfied

method cannot be called on std::result::Result<mongodb::sync::Cursor<bson::Document>, mongodb::error::Error> due to unsatisfied trait bounds

I tried using cursor.iter() or cursor.into_iter(), the result was the same

Full code of module

use bson::Document;
use mongodb::{
  error::Error,
  sync::{ Collection, Database},
};

pub struct Core {
  db: Database,
  countries: Collection<Document>,
}

impl Core {
  pub fn new(db: &Database) -> Core {
    Core {
      db: db.clone(),
      countries: db.collection("countries"),
    }
  }
  pub fn get_country(&self, name: &String) -> Result<Option<Document>, Error> {
    self.countries.find_one(bson::doc! { "idc": name }, None)
  }
  pub fn get_countries(&self) {
    let cursor = self.countries.find(None, None);
    for doc in cursor {
      println!("{}", doc?)
    }
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    My solution

    pub fn get_countries(&self) -> Vec<Document> {
      let cursor = self.countries.find(None, None).unwrap();
      let mut total: Vec<Document> = Vec::new();
      for doc in cursor {
        total.push(doc.unwrap());
      }
      total
    }
    

  2. It seems that the doc value is returning a Cursor, so I’m guessing that cursor must be rather the Result<Cursor<T>> type returned by the Collection::find method. https://docs.rs/mongodb/latest/mongodb/sync/struct.Collection.html#method.find

    Shouldn’t you unwrap (or handle the result with a proper match) your self.countries.find(None, None) result ?

    pub fn get_countries(&self) {
      let cursor = self.countries.find(None, None).unwrap();
      for doc in cursor {
        println!("{}", doc?)
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search