简体   繁体   中英

How do I add/reference objectID,name,phone etc from another collection(schema) to a new one?

I'm trying to create a simple form where the user will customize their cake and when the data save in database the user's info will be saved there also automatically. how do I do that?

this is just like any order model from e-commerce websites but I can't add the user's data in the order model automatically.

the mongoose schema I've created is like this.

const mongoose = require('mongoose');
const { required } = require('nodemon/lib/config');
const Schema=mongoose.Schema;

const customCakeSchema=Schema({
    user:{
        type:Schema.Types.ObjectId,
        ref:'saved_user'
    },
    // order_By:{
    //     type:Schema.Types.ObjectId,
    //     ref:'saved_user'
    // },
    // phone:{
    //     type:Schema.Types.ObjectId,
    //     ref:'saved_user'
    // },
    // address:{
    //     type:Schema.Types.ObjectId,
    //     ref:'saved_user'
    // },
    weight:{
        type:String,
        required:true
    },
    flavour:{
        type:String,
        required:true
    },
    shape:{
        type:String,
        required:true
    },
    layers:{
        type:Number,
        required:true
    },
    sponge:{
        type:String,
        required:true
    },
    cakeType:{
        type:String,
        required:true
    },
    creamLevel:{
        type:String,
        required:true
    },
    fondantLevel:{
        type:String,
        required:true
    },
    fondantCreamLevel:{
        type:String,
        required:true
    },
    paintCake:{
        type:String,
        required:true
    },
    fillings:{
        type:String,
        required:true
    },
    effects:{
        type:String,
        required:true
    },
    writingOnCake:{
        type:String,
        required:true
    },
    status:{
        type:String,
        default:'pending'
    },
    payment:{
        type : Boolean,
        default: false
    },
    delivered: {
        type : Boolean,
        default: false
    },
    createAt :{
        type : Date,
        default : Date.now
    }
});

const customCakeModel=mongoose.model('custom_cake',customCakeSchema);
module.exports=customCakeModel;```
const example = new custom_cake({
   user:user._id,  //<-- Need to save user id with the new data
})

To get referenced collections from the custom_cake you need to populate

custom_cake.find().populate('user').exec()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM