Node.js 猫鼬一对多关系

Node.js 猫鼬一对多关系,node.js,mongodb,express,mongoose,mongoose-schema,Node.js,Mongodb,Express,Mongoose,Mongoose Schema,我有mongoose模式和用户数据: // user schema const User = new Schema( { name: {type: String}, email: {type: String, unique: true}, // other fields }) 和用户的每日统计模式: // Stats schema const Stats = new Schema( { dateCreated: {type: Date, default: Date.now

我有mongoose模式和用户数据:

// user schema
const User = new Schema(
{
   name: {type: String},
   email: {type: String, unique: true},
   // other fields
})
和用户的每日统计模式:

// Stats schema
const Stats = new Schema(
{
  dateCreated: {type: Date, default: Date.now()},
  stepsWalked: {type: Number, default: 0},
  // other fields
  userId: String  // user id field
})
当我尝试生成具有相同用户id的多个Stats架构对象时,如下所示:

for (let i = 0; i < 40; ++i) {
  statsData = await Stats.create({
    userId: userData._id
  })
}
// user schema
const User = new Schema(
{
   name: {type: String, default: 'NaN'},
   email: {type: String, unique: true, default: 'NaN'},
   // other fields
   stats: [Stats]   // to many docs to store array in schema
})
如何实现与猫鼬的一对多关系? 我有大量针对单个用户的统计数据,因此我无法将统计数据存储为用户模式的一部分,如下所示:

for (let i = 0; i < 40; ++i) {
  statsData = await Stats.create({
    userId: userData._id
  })
}
// user schema
const User = new Schema(
{
   name: {type: String, default: 'NaN'},
   email: {type: String, unique: true, default: 'NaN'},
   // other fields
   stats: [Stats]   // to many docs to store array in schema
})

我有一个类似的问题,我得到重复的关键错误。对我来说,发生的事情是在一个子文档中,我以前在一个字段上指定了唯一的约束。在纠正之后,我继续得到错误。所以我可以创建一个实例,但在创建第二个实例时总是会出错


对我来说,另一位评论员提到的解决办法是删除该收藏。在我放弃集合后,新文档和子文档的创建工作正常

错误与您的架构不匹配。在过去的某个时候,您是否偶然在
用户ID
上创建了一个唯一的索引?如果是的话。还可以接受文档数组。我会先创建40个文档,然后调用
Stats.create(docs)
一次,而不是循环创建40次。这很有效!谢谢,你救了我一天!