![](/img/trans.png)
[英]How to add reference of one schema to another in Mongoose and inserting data by json?
[英]How do I add/reference objectID,name,phone etc from another collection(schema) to a new one?
我正在尝试创建一个简单的表单,用户可以在其中自定义蛋糕,并且当数据保存在数据库中时,用户的信息也会自动保存在那里。 我怎么做?
这就像来自电子商务网站的任何订单 model 但我无法自动将用户数据添加到订单 model 中。
我创建的 mongoose 架构是这样的。
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
})
要从您需要填充的 custom_cake 中获取引用 collections
custom_cake.find().populate('user').exec()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.