我想将用户的子对象“愿望清单”保存为ID,而不是整个对象,以避免存储重复的对象。 类似于在nodejs中使用'type:mongoose.Schema.types.ObjectId'和'ref:'WishList'进行操作的方式,但是在C#中使用。
如何在nodejs中完成
let UserSchema = new
mongoose.Schema({
Email: String,
wishlists: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'WishList'
}
],
Username: {
type: String,
lowercase: true,
unique: true
}
});
在MongoDB中应该如何:
{
"_id": {
"$oid": "5b4c40c9470c5e26e0e55359"
},
"Username": "gilles",
"Email": "",
"Wishlists": [
{
"$oid": "5b5ae2914015fb3028582ea6"
}
],
}
现在如何保存:
{
"_id": {
"$oid": "5b4c40c9470c5e26e0e55359"
},
"Username": "gilles",
"Email": "",
"WishLists": [
{
"_id": {
"$oid": "5b5ae2914015fb3028582ea6"
},
"Name": null,
"Members": null,
"Wishes": null
}
],
}
ASP.net中的代码:
public class User
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public List<WishList> WishLists { get; set; }
}
public class WishList
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public List<string> Members { get; set; }
public List<WishItem> Wishes { get; set; }
}
public class UserRepository : IUserRepository {
private readonly ObjectContext _context = null;
public UserRepository(IOptions<Settings> settings)
{
_context = new ObjectContext(settings);
}
public async Task Add(User user)
{
await _context.Users.InsertOneAsync(user);
}
}
public class ObjectContext {
public IConfigurationRoot Configuration { get; }
private IMongoDatabase _database = null;
public IMongoCollection<User> Users
{
get
{
return _database.GetCollection<User>("Users");
}
}
}