本文介绍了如何在猫鼬的嵌套填充中选择特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的架构:
var UserSchema = new Schema({
email: String,
name: String,
city: String,
username: String,
profilePic: String,
phoneNo: Number,
shortList: {
project: [{ type: Schema.ObjectId, ref: "Project" }],
flat: [{ type: Schema.ObjectId, ref: "Flat" }],
},
});
var FlatSchema = new Schema({
project: { type: Schema.ObjectId, ref: "Project" },
status: String,
floor: Number,
size: String,
type: String,
flat_number: String,
price: Number,
flooringType: String,
createdAt: { type: Date, 'default': Date.now },
isDeleted: { type: Boolean, 'default': false },
});
var ProjectSchema = new Schema({
name: String,
shortName: String,
developer: { type: Schema.ObjectId, ref: "Developer" },
address: {
street_address: String,
city: String,
state: String,
pin: Number,
position: {
lat: Number,
long: Number
}
},
ofcAddress: {
street_address: String,
city: String,
state: String,
pin: Number,
},
overview: {
size: String,
area: String,
configuration: String,
possession_starts: Date,
info: String,
aminities: [{ type: Schema.ObjectId, ref: "Amenity" }]
},
images: {
hdpi: String,
xhdpi: String,
web: String,
mdpi: String
},
});
此处用户与 flat 模型 shortList.flat 链接,而 flat 模型与项目
here user link with flat model shortList.flat and flat model is link with the project
现在我正尝试选择所有详细信息,如下所示:
now i am trying to select all details as follow:
User.findById(req.params.id)
.populate('shortList.project', { 'CalculationsRules': 0, 'KBFlatTypeCharges': 0, 'CategoryPremia': 0, 'Floor': 0, 'KBUnitType': 0, 'floorplans': 0, 'flats': 0, 'towers': 0, 'galaryImages': 0 })
.populate('shortList.flat', { 'pricedetails': 0 })
.exec((err, user) => {
if (err) { return handleError(res, err); }
if (!user) { return res.json(401); }
//here i want to select specific field from project model
User.populate(user, { path: 'shortList.flat.project', model: 'Project' }, (err, user) => {
res.status(200).json(user);
})
});
它工作正常,但我想从项目模型中选择一些特定的字段,例如名称和图像
its working fine but i want to select some specific fields form project model like name and images
推荐答案
在其中使用select属性填充为:
Use select property in populate as:
User.populate(user, { path: 'shortList.flat.project', model: 'Project', select: 'name' })
这只会给您项目的名称.
This will give you name of project only.
要指定不需要的字段,可以将其设置为零,
To give specify fields which you don't want you can zero as:
User.populate(user, { path: 'shortList.flat.project', model: 'Project', select: { 'name': 0, 'Floor': 0, 'flats': 0, 'towers': 0,} }
这对我有用.
,如果您要进行两个级别的填充:
and if you are doing two level populations:
我们可以简单地这样做:
we can simply do it as:
populate('project.tower', 'name project flats');
简单填充以获取特定领域:
for a simple populate to get specific feilds:
populate('project', 'name')
这篇关于如何在猫鼬的嵌套填充中选择特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!