Understanding Relationships & Foreign Keys in Mongoose

后端 未结 1 1790
粉色の甜心
粉色の甜心 2021-02-07 04:09

In MongoDB/Mongoose, how do I define a relationship? I think there are a few ways I\'ve seen, but I\'m not sure I understand the differences or when do I use which. I am using M

相关标签:
1条回答
  • 2021-02-07 04:24

    I'm still new to Node, Mongoose, and Mongo, but I think I can address at least part of your question. :)

    Your current method is the same as I tried doing at first. Basically, it ends up storing it very similarly to this (written in JS, since I don't know CoffeeScript):

    var todoListSchema = new mongoose.Schema({
        name: String,
        todos: [{
            name: String,
            desc: String,
            dueOn: Date,
            completedOn: Date
        }]
    });
    

    I later found this method, which is what I was looking for, and I think what you were intending:

    var todoListSchema = new mongoose.Schema({
        name: String,
        todos: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Todo' //Edit: I'd put the schema. Silly me.
        }]
    });
    

    This stores an array of ObjectIds, which you can then load using Query#populate in Mongoose.

    I don't know of the technical implications, but it makes more sense in my brain if I keep them separate, so that's what I'm doing. :)

    Edit: Here is a some official docs that might be useful: http://mongoosejs.com/docs/populate.html

    0 讨论(0)
提交回复
热议问题