问题描述
我为此苦了几天。从理论上讲,这很容易(至少在SQL中是这样)。
我有3个收藏集,预订,软件包和个人资料
每个与预订相关联的预订(嵌套文档/预订附带),每个与包装相同的配置文件作为个人资料都可以附加到包装上,好吗?
我只想查询一个查询,该查询返回所有预订,但将包裹作为已删除的配置文件除外,这意味着配置文件不再存在于数据库中,它永远都不会发生,因为每个包裹必须关联一个配置文件,但以防万一我想学习如何处理这种查询。
这是查询:
filter = { $and: [ {
'package' : { $exists: true },'status': {$ne: 'deleted'}
}
]
};
return Booking.find( filter )
.populate(
[
{
path: 'package',model: 'Package',select : 'title description duration_minutes profile service',populate : [
{
path : 'profile',model: 'Profile',select : '_id name photo_profile',match: { '_id' : { $exists: true,$ne: null}},// match: { 'name' : { $exists: true,}
]
}
]
)
.sort( { date: -1 } )
.exec();
这些是模式: 预订:
const bookingSchema = new Schema( {
created_at: {
type: String,default: moment().format('llll')
},package: {
type: Schema.Types.ObjectId,ref: 'Package',required: [ true,'A reference to a package must exist']
},status: {
type: String // ['pending','confirmed','finished']
},});
包装:
const packageSchema = new Schema( {
created: {
type: Date,default: Date.now
},title: {
type: String,'A title is mandatory']
},profile: {
type: Schema.Types.ObjectId,ref: 'Profile','A reference to a profile must exist']
},service: {
type: Schema.Types.ObjectId,ref: 'Service','A reference to a service must exist']
},price_in: {
type: Number
},});
个人资料:
const profileSchema = new Schema( {
created_at: {
type: Date,name: {
type: String
},address: {
type: String
// required: [ true,'An address to must exist']
},geopoint: {
type: { type: String },coordinates: [] // lat,lng
},photo_profile: {
type: String,default: 'user.jpg'
},active: {
type: Boolean,default: true
},user: {
type: Schema.Types.ObjectId,ref: 'User','A reference to a user must exist']
},});
放什么都没关系
匹配项:{'_id':{$存在:true,$ ne:空}}
因为查询也返回配置文件NULL,这意味着不存在的配置文件,我真的不知道如何为嵌套文档执行“ where”子句。
在当前情况下,当我尝试读取空配置文件时,出现此错误:
err TypeError:无法读取null的属性“ _id”
当然,bookings [key] .package.profile不会退出,但是,如何避免使用NON EXISTING配置文件进行预订?这是主要问题。
注意:我知道我可以通过 .map函数或类似的代码来过滤结果,但我确实想学习并在查询中完成
我只是想添加更多信息,以防万一我的问题不清楚。 这是我在控制台中使用console.log时得到的转储。
这是一个响应示例,我得到了一些正确的结果(填充了现有的配置文件),但有些配置文件为NULL(因为此配置文件不再存在)。我真的需要从查询结果中忽略此预订,是否可以只进行一次查询?
{
requesters: 1,_id: sdfdsf43535353,date: 1595916000,buyer: { _id: dfsdf43535345353 },package: {
duration_minutes: 60,_id: 5ee604103df1d70017ad12a7,service: null,title: ‘lorem ‘ipsum,description: ‘lorem ipsum;
profile: null
}
{
requesters: 1,_id: 5f6580eff34gfgfdg730251e,date: 1600527600,buyer: { _id: 5eeb26efdfdfdddfc0017c76e50 },package: {
duration_minutes: 60,_id: 5f016c3192e71a00178ebc45,service: { _id: 5ee1bd48afgfg760a080,name: ‘lorem ipsum },profile: {
photo_profile: 'ccddfdfdCCCCC.jpeg',_id: 5efeca84f0bcbd0017d708eb,name: '99 cool deal'
},},
非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)