Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose Foreign Key

I have a model called Portfolio that points to a user object using the user_id field. How can I model a many to one relationship with mongoose?

Portfolio - user_id => is the id of a user object

Basically every portfolio object belongs to a user object.

I have the following code: Is this correct?

var PortfolioSchema = mongoose.Schema({
    url: String,
    createTime: { type: Date, default: Date.now },
    updateTime: { type: Date, default: Date.now },
    user:[
      {type: Schema.Types.ObjectId, ref: 'User'}
    ]
});
like image 986
Chris Hansen Avatar asked May 19 '26 07:05

Chris Hansen


1 Answers

Try this instead

var PortfolioSchema = mongoose.Schema({
    url: String,
    createTime: { type: Date, default: Date.now },
    updateTime: { type: Date, default: Date.now },
    user:{type: Schema.Types.ObjectId, ref: 'User'}
});
like image 125
Marcel Djaman Avatar answered May 21 '26 23:05

Marcel Djaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!