如何填充 mongodb 中的多个表以在 ejs 中显示?
How to populate multiple tables in mongodb to display in ejs?
我创建了三个模式。这里,动物模式引用物种模式,物种模式引用特殊信息模式。
var animal = new mongoose.Schema({
name:String,
info:String,
species:[{
type:mongoose.Schema.Types.ObjectId,
ref:species
}]
});
var species = new mongoose.Schema({
name:String,
sound:String,
speicalinfo:[{
type:mongoose.Schema.Types.ObjectId,
ref:specialinfo
}]
});
var specialinfo = new mongoose.Schema({
history:String,
speciafeature:[]
});
我想填充动物模式,这样我也可以访问特殊信息数据。
这是我获取索引页的请求函数。
app.get('/index', (req,res)=>{
animal.findById(id).populate('species').exec(function (err, animal) {
if (err) {return handleError(err);}
res.render('index',{
animal: animal
});
});
})
我想从索引页访问 specialinfo 模式的历史和特殊功能字段。我怎样才能做到这一点?
谢谢!
animal.findById(id).populate({path: 'species',populate: { path: "specialinfo" },})
猫鼬自动填充
您可以使用'mongoose-autopopulate'并获取自动填充的数据,然后您可以填充物种
npm i mongoose-autopopulate
https://www.npmjs.com/package/mongoose-autopopulate
import mongooseAutopopulate from 'mongoose-autopopulate';
var animalSchema = new mongoose.Schema({
name: String,
info: String,
species: [{
type: mongoose.Schema.Types.ObjectId,
ref: species,
autopopulate: true
}]
);
animalSchema.plugin(mongooseAutopopulate);
我创建了三个模式。这里,动物模式引用物种模式,物种模式引用特殊信息模式。
var animal = new mongoose.Schema({
name:String,
info:String,
species:[{
type:mongoose.Schema.Types.ObjectId,
ref:species
}]
});
var species = new mongoose.Schema({
name:String,
sound:String,
speicalinfo:[{
type:mongoose.Schema.Types.ObjectId,
ref:specialinfo
}]
});
var specialinfo = new mongoose.Schema({
history:String,
speciafeature:[]
});
我想填充动物模式,这样我也可以访问特殊信息数据。
这是我获取索引页的请求函数。
app.get('/index', (req,res)=>{
animal.findById(id).populate('species').exec(function (err, animal) {
if (err) {return handleError(err);}
res.render('index',{
animal: animal
});
});
})
我想从索引页访问 specialinfo 模式的历史和特殊功能字段。我怎样才能做到这一点? 谢谢!
animal.findById(id).populate({path: 'species',populate: { path: "specialinfo" },})
猫鼬自动填充
您可以使用'mongoose-autopopulate'并获取自动填充的数据,然后您可以填充物种
npm i mongoose-autopopulate
https://www.npmjs.com/package/mongoose-autopopulate
import mongooseAutopopulate from 'mongoose-autopopulate';
var animalSchema = new mongoose.Schema({
name: String,
info: String,
species: [{
type: mongoose.Schema.Types.ObjectId,
ref: species,
autopopulate: true
}]
);
animalSchema.plugin(mongooseAutopopulate);