Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

mongoose - Mongoosejs / Mongodb - Nested Data vs New Model

I am writing a node.js webapp using mongodb/mongoosejs. I have a user and a car model and want to keep history of the car. I know there is no right or wrong way to do these things but I am wondering what is the better options.

Option 1: New model that holds the Car and User with dateto and datefrom

const usercarsSchema = new mongoose.Schema({
    car : {
        type : mongoose.Schema.Types.ObjectId,
        ref : 'Car'
    },
    user : {
        type : mongoose.Schema.Types.ObjectId,
        ref : 'User'
    },
    datefrom : Date,
    dateto : Date
}

Option 2: Nested History Within The Car Model

const carSchema = new mongoose.Schema({
    owner : [{
        user : {
            type : mongoose.Schema.Types.ObjectId,
            ref : 'User'
        },
        datefrom : Date,
        dateto : Date
    }]
}

I'm pretty new to mongodb and in the past using MYSQL this would have been three tables. But with Mongodb I can see a nested way of doing it. Which option is the better way of doing this?

question from:https://stackoverflow.com/questions/65866152/mongoosejs-mongodb-nested-data-vs-new-model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My personal advice is to avoid nested history inside the array. Why is that? Simply because it's the most popular anti-pattern.

It will be hard for you to receive result docs from $lookup. Mainly because of 16MB BSON limit.

I am using Mongo in my production project and I really have face this frustrating issue by myself. So the lesson was learned.

But don't get me wrong. Arrays are fine until you don't store in them too much data.

First is __v (versioning) field and the second is working with $.index. (Take a look at Mongoose Driver Doc for arrays) It's pretty awesome, if you are working with Mongoose / non-lean documents.

Also, in MongoDB, you could build indexes for fields in an array of objects, so it might help you with query performance and optimization.

So, in your case, I would choose to create New Model and take a look at these articles from Mongo University about schema architecture and patterns , which might be very useful for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...