I am trying to retireve all the documents in my MongoDB collection via a REST api built in ASP.NET MVC 4 and I have encoutered an error when i enter localhost:50491/api/document:
An error occurred while deserializing the Id property of class Acord_Rest_API.Models.Document: Cannot deserialize string from BsonType ObjectId.
My controller looks like:
public class DocumentController : ApiController
{
public readonly MongoConnectionHelper<Document> docs;
public DocumentController()
{
docs = new MongoConnectionHelper<Document>();
}
public IList<Document> getAllDocs()
{
var alldocs = docs.collection.FindAll();
return alldocs.ToList();
}
}
My MongoDB document looks like this?
What am I missing here?
My class that connects to the DB:
public class MongoConnectionHelper<T> where T: class
{
public MongoCollection<T> collection { get; private set; }
public MongoConnectionHelper()
{
string connectionString = "mongodb://127.0.0.1";
var server = MongoServer.Create(connectionString);
if (server.State == MongoServerState.Disconnected)
{
server.Connect();
}
var conn = server.GetDatabase("Acord");
collection = conn.GetCollection<T>("Mappings");
}
}
EDIT here is my solution:
MongoConnectionHelper does the connection to the DB, DocumentController has the methods to retrive all the documents and Document contains what you have suggested in your answer.
EDIT here is the Document class:
[DataContract]
public class Document
{
public ObjectId _id { get; set; }
[DataMember]
public string MongoId
{
get { return _id.ToString(); }
set { _id = ObjectId.Parse(value); }
}
public IList<string> alldocs { get; set; }
}
A more simple approach is to tell MongoDB to treat string field as ObjectId.
You can do it easily by using BsonType
attribute.
[BsonRepresentation(BsonType.ObjectId)]
public string _id { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With