我的数据库中的文档是用 node.js 创建的。 https://github.com/mongodb/node-mongodb-native 我正在使用 mongodb c# 驱动程序,当我尝试访问它们时出现错误。我猜 node.js 驱动程序创建的 objectid 与 c# 驱动程序创建的 objectid 不同。
Unhandled Exception: System.IO.FileFormatException: An error occurred while deserializing the _id property of class trader.Formula: 'CD2j7m4qDLMowGCXi' is not a valid 24 digit hex string. ---> System.FormatException: 'CD2j7m4qDLMowGCXi' is not a valid 24 digit hex string.
at MongoDB.Bson.ObjectId.Parse(String s)
at MongoDB.Bson.Serialization.Serializers.ObjectIdSerializer.Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializati onOptions options)
at MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeMemberValue(BsonReader bsonReader, BsonMemberMap memberMap)
--- End of inner exception stack trace ---
at MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeMemberValue(BsonReader bsonReader, BsonMemberMap memberMap)
at MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
at MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
at MongoDB.Driver.Internal.MongoReplyMessage`1.ReadFrom(BsonBuffer buffer, IBsonSerializationOptions serializationOptions)
at MongoDB.Driver.Internal.MongoConnection.ReceiveMessage[TDocument](BsonBinaryReaderSettings readerSettings, IBsonSerializer serializer, IBsonSerializationOptions serializationOptions)
at MongoDB.Driver.MongoCursorEnumerator`1.GetReply(MongoConnection connection, MongoRequestMessage message)
at MongoDB.Driver.MongoCursorEnumerator`1.GetFirst()
at MongoDB.Driver.MongoCursorEnumerator`1.MoveNext()
我该如何解决这个错误?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace trader
{
public class Formula
{
public ObjectId _id { get; set; }
public string name { get; set; }
}
class Program
{
static void Main(string[] args)
{
MongoClient client = new MongoClient("mongodb://localhost:27017");
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("trader");
var formulaCollection = db.GetCollection<Formula>("formulas");
var formulas = formulaCollection.FindAll();
foreach (var formula in formulas)
{
Console.WriteLine(formula.name);
}
}
}
}
这是来自 db.formulas.find({}, {name:1})
{ "_id" : "9RZuitaJ7uKvrBKbE", "name" : "10d sma" }
{ "_id" : "kjLzXChio8wD2MQcD", "name" : "< 10d mean" }
{ "_id" : "mmjSnHS5L2GztXPLX", "name" : "< 2h mean" }
{ "_id" : "bH5zBEz5CnMFJMnSZ", "name" : "< 2h mean > 0.4 sd2h" }
{ "_id" : "A2joSNeBxPZTJgkGs", "name" : "< 2d mean > 0.4 sd2d" }
{ "_id" : "6jgQvFci3mW5Aijr6", "name" : "< 2d mean > 0.4 sd2d 2h sma" }
{ "_id" : "hHBRtu2nWZiYBdHGq", "name" : "2d sma" }