AndrewLeonardi
AndrewLeonardi

Reputation: 3512

Save Mongo/Mongoose Object within another Model

I have a Mongo object that looks like this:

var foodSchema = new mongoose.Schema({
   name:      { type: String, required: false, unique: true },
   image:     { type: String, required: false, unique: true },
});

The idea is to be able to save a "food" object to a user. (The data comes from a seed file.)

So if the data going into the model above was:

name: tacos, 
image: tacos.gif 

What I want to be able to do is then save that data to a user model. Is the best way to go about this to have a field in the user model to save the data? (Saving to last two fields) Such as:

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    foodName1: String,
    foodImage1: String, 
});

To me this seems like I'm saving the data twice, within two difference models. Is this the correct way to handle this? Or is there a better way to store the food data inside the user's model?

Upvotes: 1

Views: 3724

Answers (1)

Dracks
Dracks

Reputation: 107

u can replace foodName1: String, foodImage1: String by :

food: {id: { type: Schema.Types.ObjectId, ref: 'foodSchema'}

and after when u retrieve foodSchema use populate https://mongoosejs.com/docs/populate.html

if you need more than one foodSchema

food: [{id: { type: Schema.Types.ObjectId, ref: 'foodSchema'}]

for save juste create food object and put on existing user or new created user:

let user = new UserSchema({'user info here'})
let food = new foodSchema({name: 'test',image: 'test'});
user.food = food
user.save().then(() => {

})

or for push a food in a food array on existing user:

UserSchema.findById(req.body.id).exec((err, docc) => {
                docc.food.push(food)
                docc.save((err, result) => {
                    if (err)
                        res.sendStatus(500);
                    res.sendStatus(200);
                })
            })

otherwise we can just add the _id of the food object, but it's less visual

Upvotes: 3

Related Questions