Node.js 猫鼬|在所有功能上保持相同的种群
我的作物模型有这个模式 此模式适用于我的区域模型 此模式适用于我的条件模型 这是我的控制模型的模式 我获取节点中所有作物的方式如下: 我获得单个作物的方式如下: 如您所见,部分: .populate({..}) 重复两次。Node.js 猫鼬|在所有功能上保持相同的种群,node.js,angular,mongoose,mean-stack,mongoose-populate,Node.js,Angular,Mongoose,Mean Stack,Mongoose Populate,我的作物模型有这个模式 此模式适用于我的区域模型 此模式适用于我的条件模型 这是我的控制模型的模式 我获取节点中所有作物的方式如下: 我获得单个作物的方式如下: 如您所见,部分: .populate({..}) 重复两次。 如何保持相同的填充配置,以便不必一直编写/更新相同的内容?您可以将填充对象保存为变量并共享它: const zonePopulateObj = { path: 'zones', populate: [ { path: 'poor', populat
如何保持相同的填充配置,以便不必一直编写/更新相同的内容?您可以将填充对象保存为变量并共享它:
const zonePopulateObj = {
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
};
然后在你的询问中
return Crop.find().populate(zonePopulateObj).exec();
return Crop.findById(req.params.id).populate(zonePopulateObj).exec();
或者,您可以将查询逻辑拉入一个新函数并共享它
public index(req: Request, res: Response) {
return findCrop()
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
public show(req: Request, res: Response) {
return findCrop(req.params.id)
.then((array)=>array.length ? array[0] : {})
.then(handleEntityNotFound(res)) // may need to update this function not sure how it checks for not found.
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
const findCrop = (id)=>{
let queryObj = {};
if(id){
queryObj._id=id
}
return Crop.find(queryObj).populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
}
就我个人而言,我更喜欢第一种方法
var ControlSchema = new mongoose.Schema({
name: String,
...
});
public index(req: Request, res: Response) {
return Crop.find().populate('zones').populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
public show(req: Request, res: Response) {
return Crop.findById(req.params.id).populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
.then(handleEntityNotFound(res))
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
const zonePopulateObj = {
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
};
return Crop.find().populate(zonePopulateObj).exec();
return Crop.findById(req.params.id).populate(zonePopulateObj).exec();
public index(req: Request, res: Response) {
return findCrop()
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
public show(req: Request, res: Response) {
return findCrop(req.params.id)
.then((array)=>array.length ? array[0] : {})
.then(handleEntityNotFound(res)) // may need to update this function not sure how it checks for not found.
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
const findCrop = (id)=>{
let queryObj = {};
if(id){
queryObj._id=id
}
return Crop.find(queryObj).populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
}