How to add a model inside another model with mongoose and node js

Viewed 1404

I am working on a project and am trying to add a model inside another model but i can't seem to figure out how to do it. Have any suggestions? `

const userSchema = new mongoose.Schema({
    first_name: String,
    last_name: String,
    email: String,
    password: String,
});

const ItemSchema = new mongoose.Schema({
    date: String,
    loc: String,
    title: String,
   passage: String,
   file: String
});

const User = mongoose.model("User", userSchema);
const Item = mongoose.model("Item", ItemSchema);

const user1 = new User({
    first_name: "John",
    last_name: "arbuckle",
    email: "blablabal@asdf",
    password: "123456789"
});

const item1 = new Item({
    date: "Today",
    loc: "here",
    title: "message",
    passage: "This is an example",
    file: "none"
});

I am wanting to add this model const Item = mongoose.model("Item", ItemSchema); to the User model.

1 Answers

You are looking for population.

In userSchema add items : { type: [Schema.Types.ObjectId], ref: 'Item' }

const userSchema = new mongoose.Schema({
    first_name: String,
    last_name: String,
    email: String,
    password: String,
    items : {
         type: [Schema.Types.ObjectId],
         ref: 'Item'
    }
});

const ItemSchema = new mongoose.Schema({
    date: String,
    loc: String,
    title: String,
   passage: String,
   file: String
});
Related