居住在猫鼬 [英] Populate in Mongoose
问题描述
我需要一些帮助来使用 mongoose 填充子文档,我在互联网上搜索了很多,但没有找到解决问题的方法.
I need some help to populate on sub-document with mongoose, I searched a lot in the internet , but didn't find a way to fix my problem.
我有两个架构:1 - 基础设施
I heve two schema : 1 - InfraServer
var InfraServerSchema = new Schema({
_id : String,
equipe : String,
servidor : String,
memoria : String,
processador : String,
modelo : String,
so : String,
usuario : String
},{ collection: 'infraserver' });
var InfraServer = mongoose.model('InfraServer', InfraServerSchema);
module.exports = InfraServer;
2 - 基础设施数据库
2 - InfraDataBase
var InfraDataBaseSchema = new Schema({
_id : String,
equipe : String,
nome_base : String,
vipname : String,
tipo_banco : String,
versao: String,
servidores : [{ type : mongoose.Schema.Types.ObjectId, ref: 'InfraServer' }],
tnsnames : String
},{ collection: 'infradatabase' });
var InfraDataBase = mongoose.model('InfraDataBase', InfraDataBaseSchema);
module.exports = InfraDataBase;
我正在尝试在路由文件夹中填充如下所示的数组 servidores,但是当我打印种子变量时,数组返回空,并且需要 servidores.servidor(InfraServer 中的字段)、servidores._id 正确填充.
I'm trying to populate the array servidores like below, in routes folder, but when I print seeds variable, the array return empty, and need the servidores.servidor (field in InfraServer), servidores._id are populate correctly.
InfraDataBase.find().where('equipe').in(req.session.userInf.equipe).populate('servidores').exec(function(err, seeds){
if( err || !seeds) console.log("No seeds found");
else
{
console.log("--->>> " + seeds);
}
可以帮我找到解决这个问题的方法.
Can help me find a way to resolve this problem .
谢谢
推荐答案
尝试将 _id 的 SchemaType 更改为 ObjectId.
Try changing the SchemaType of the _id to ObjectId.
_id : ObjectId
此外,您不需要显式声明 _id 字段.它是为所有 Mongoose 模式自动创建的.
Besides, you don't need to explicitly declare the _id field. It is automatically created for all Mongoose schemas.
这篇关于居住在猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!