简体   繁体   中英

Mongoose one to many relationship

I have mongoose schema with User data:

// user schema
const User = new Schema(
{
   name: {type: String},
   email: {type: String, unique: true},
   // other fields
})

And User's daily statistics schema:

// Stats schema
const Stats = new Schema(
{
  dateCreated: {type: Date, default: Date.now()},
  stepsWalked: {type: Number, default: 0},
  // other fields
  userId: String  // user id field
})

When i trying to generate multiple Stats schema objects with the same user id like this:

for (let i = 0; i < 40; ++i) {
  statsData = await Stats.create({
    userId: userData._id
  })
}

I'm getting mongoose duplicate exception on second iteration of the loop. Stack trace:

MongoError: E11000 duplicate key error collection: 5909aed3df9db12e2b71a579_.stats index: userId_1 dup key: { : "5991c027a572690bfd322c08" }
at Function.MongoError.create (node_modules/mongodb-core/lib/error.js:31:11)
at toError (node_modules/mongodb/lib/utils.js:139:22)
at node_modules/mongodb/lib/collection.js:669:23
at handleCallback (node_modules/mongodb/lib/utils.js:120:56)
at node_modules/mongodb/lib/bulk/unordered.js:465:9
at handleCallback (node_modules/mongodb/lib/utils.js:120:56)
at resultHandler (node_modules/mongodb/lib/bulk/unordered.js:413:5)
at node_modules/mongodb-core/lib/connection/pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

How can i implement one-to-many relationship with mongoose ? I have huge amount of stats data for single user, so i can't store stats data as part of User schema like this:

// 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
})

I had a similar issue where I was getting duplicate key errors. What happened for me was in a subdocument, I had previously assigned a unique constraint on one field. After correcting that, I continued to get the error. So I could create one instance just fine, but would always get an error when creating a second instance.

The fix for me, which is what another commenter here has mentioned, is to drop that collection. After I dropped the collection, new document and subdocument creation worked just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM