2014-10-01 136 views
0

我的模式是如下猫鼬填充问题 - 数组对象

Sectionschema

var SectionSchema = new Schema({ 
    name: String, 
documents : { 
     type : [{ 
      type: Schema.ObjectId, 
      ref: 'Document' 
     }] 
    } 
} 

} 

DocumentSchema

var DocumentSchema = new Schema({ 
    name: String, 
    extension: String, 
    access: String, //private,public 
    folderName : String, 
    bucketName : String, 
    desc: String 
}); 

Api.js

exports.section = function(req, res, next, id) { 

    var fieldSelection = { 
     _id: 1, 
     name: 1,  
     documents : 1 
    }; 

    var populateArray = []; 
    populateArray.push('documents'); 

    Section.findOne({ 
     _id: id 
    }, fieldSelection) 
     .populate(populateArray) 
     .exec(function(err, section) { 
      if (err) return next(err); 
      if (!section) return next(new Error('Failed to load Section ' + id)); 
      // Found the section!! Set it in request context. 
      req.section = section; 
      next(); 
    }); 
} 

如果我这样走,我有 '文件'对象是[]。但是,如果我删除,“populateArray.push('文件');”那么我得到的文件:['5adfsadf525sdfsdfsdfssdfsd'] - 一些对象Id(至少)

请让我知道我需要填充的方式。

谢谢。

回答

1

查询更改为

Section.findOne({ 
     _id: id 
    }, fieldSelection) 
     .populate('documents.type') 
     .exec(function(err, section) { 
      if (err) return next(err); 
      if (!section) return next(new Error('Failed to load Section ' + id)); 
      // Found the section!! Set it in request context. 
      req.section = section; 
      next(); 
    }); 

和工作原理。您需要提供填充路径。

0

如果您只是希望模式中的“文档”指向稍后将填充的ObjectID数组。那么你可以使用这个。

var SectionSchema = new Schema({ 
name: String, 
documents : [{ 
     type: Schema.ObjectId, 
     ref: 'Document' 
    }]  
}); 

,并使用以下填充它

Section.findOne({ 
     _id: id 
    }, fieldSelection) 
     .populate('documents') 
     .exec(function(err, section) { 
      if (err) return next(err); 
      if (!section) return next(new Error('Failed to load Section ' + id)); 
      // Found the section!! Set it in request context. 
      req.section = section; 
      next(); 
    });