在Mongodb中,每个记录都必须有一个唯一的主键。在ASP.NET Core中使用Mongodb时,我们需要设置主键。 以下是使用C#和Mongodb.Driver包的示例代码:
使用Id属性作为主键 public class MyDocument { public ObjectId Id { get; set; } public string Name { get; set; } }
使用自定义属性作为主键 public class MyDocument { [BsonId] public string MyId { get; set; } public string Name { get; set; } }
在代码中设置主键 public class MyDocument { public string Id { get; set; } public string Name { get; set; }
public MyDocument() { this.Id = Guid.NewGuid().ToString(); } }
从前端生成主键 在前端创建记录时,可以生成一个唯一的主键,并将其传递给后端。 例如:在Angular中,可以使用ngx-uuid库生成一个唯一的ID。
import { v4 as uuidv4 } from 'uuid';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
id = uuidv4();
name = "";
constructor(private http: HttpClient) { }
save() { const data = { id: this.id, name: this.name }; this.http.post("/api/my-collection", data).subscribe(() => { // saved successfully }); } }
无论哪种方法,都必须注意在Mongodb中使用唯一的主键。