gpt4 book ai didi

javascript - 仅在满足条件时填充

转载 作者:行者123 更新时间:2023-11-29 23:42:20 24 4
gpt4 key购买 nike

我有一个 mongodb 数据库,我将 mongoose 与 nodejs 结合使用。

仅当我有字段“temtussvinculado=true”时,我才需要从填充“tabela_tuss”的下一个查询返回数据。

这是我正在做的:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
.populate('convenioId')
.populate({
path:'procedId',
populate:{
path:'tabela_tuss',
match: { 'procedId.temtussvinculado': true}
}
})
.exec( (err,data) => {
callback(err,data,res)
})

我的问题是我与“procedId.temtussvinculado:true”的匹配没有效果,并且“tabela_tuss”从未被填充。

我做错了什么?

这是我的模式:

////
var conveniosSchema = new mongoose.Schema({
nome: {type: String, unique:true},
ativo: {type: Boolean}
});
module.exports = mongoose.model('Convenio', conveniosSchema,'convenios' );
////

////
const agProcedimentosSchema = new mongoose.Schema({
ativo:{type:Boolean},
temtussvinculado:{type:Boolean},
tabela_tuss:{type:mongoose.Schema.Types.ObjectId, ref:'Tuss_22'}
});
module.exports = mongoose.model('Ag_procedimento', agProcedimentosSchema,'ag_procedimentos' );
///

////
const tuss_22Schema = new mongoose.Schema({
codigo: {type: String, unique:true},
descricao:{type: String},
tabela:{type: String}
});
module.exports = mongoose.model('Tuss_22', tuss_22Schema,'tuss_22' );
////

//../models/convenioprocedimento
var conveniosProcedsSchema = new mongoose.Schema({
convenioId:{type:mongoose.Schema.Types.ObjectId, ref:'Convenio'},
procedId:{type:mongoose.Schema.Types.ObjectId, ref:'Ag_procedimento'},
valor_particular:{type:Number},
valor_convenio:{type:Number},
});

module.exports = mongoose.model('ConvenioProcedimento', conveniosProcedsSchema,'conveniosprocedimentos' );

//my query:

const ConvProced = require('../models/convenioprocedimento');
ConvProced.find({'convenioId':new ObjectId(req.params.id)})
.populate('convenioId')
.populate({
path:'procedId',
populate:{
path:'tabela_tuss',
match: { 'procedId.temtussvinculado': true}
}
})
.exec( (err,data) => {
callback(err,data,res)
})

最佳答案

您在这里实际要问的是“仅在数据中的条件要求这样做的地方填充”,这实际上并不是.populate() 的“直接”支持操作。或使用“嵌套填充”语法。

因此,如果您想对实际填充或不填充项目施加“条件”,那么您必须“手动”处理填充调用。

您的情况的基本前提是您需要检查需要从“初始”顶层获得的值 .populate()调用,但随后“仅”在给定条件实际允许时调用“内部”填充。

所以你的代码应该看起来像这样使用“Promises”使用 Promise.all()你基本上“循环”或.map()每个查询结果并测试 proceedid.temtussvinculado 以查看它是否为 true/false,而 true 我们实际发出一个 Model.populate()调用,否则只返回当前状态的数据:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
.populate('convenioId procedId')
.exec()
.then(data =>
Promise.all(
data.map( d =>
( d.proceedid.temtussvinculado )
? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' })
: d
)
)
)
)
// Populated conditionally
.then( data =>
// Do something with data
)
.catch(err => console.error(err)); // or something else with error

除了“Promises”之外还有其他可用选项,但它是无依赖选项。其他情况,例如 async.map做同样的事情,但如果你还没有它,那就是一个额外的依赖:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
.populate('convenioId procedId')
.exec((err,data) => {
if (err) throw err;
async.map(data,(d,callback) =>
( d.proceedid.temtussvinculado )
? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' },callback)
: callback(null,d)
(err,data) => {
if (err) throw err; // or something
// Conditionally populated
}
)
})

还用一个完整的工作示例进行了演示,这实际上比您需要做的要复杂一点,因为在这个示例中“条件”嵌套在另一个数组中:

const async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

mongoose.connect('mongodb://localhost/test');


const subInnerSchema = new Schema({
label: String
});

const innerSchema = new Schema({
name: String,
populate: Boolean,
subs: [{ type: Schema.Types.ObjectId, ref: 'Sub' }]
});

const outerSchema = new Schema({
title: String,
inners: [{ type: Schema.Types.ObjectId, ref: 'Inner' }]
});

const Sub = mongoose.model('Sub', subInnerSchema);
const Inner = mongoose.model('Inner', innerSchema);
const Outer = mongoose.model('Outer', outerSchema);

function log(data) {
console.log(JSON.stringify(data, undefined, 2))
}

async.series(
[
// Clean data
(callback) =>
async.each(mongoose.models,(model,callback) =>
model.remove({},callback),callback),

// Insert some data
(callback) =>
async.waterfall(
[
(callback) =>
Sub.create([1,2,3,4].map( label => ({ label })),callback),

(subs,callback) =>
Inner.create(
[0,2].map(x => subs.slice(x,x+2))
.map((el,i) => ({
name: i+i,
populate: i == 1,
subs: el
})),
callback
),

(inners,callback) =>
Outer.create(
inners.map((inner,i) => ({
title: i+1,
inners: [inner]
})),
callback
),

],
callback
),

// Conditional populate async.map version
(callback) =>
Outer.find().populate('inners').exec((err,outers) => {
if (err) callback(err);

async.map(
outers,
(outer,callback) =>
async.map(
outer.inners,
(inner,callback) =>
(inner.populate)
? Inner.populate(inner,{ path: 'subs' },callback)
: callback(null,inner),

(err,inners) => {
if (err) callback(err);
outer.inners = inners
callback(null,outer);
}
),

(err,outers) => {
if (err) callback(err);
log(outers);
callback();
}
);
}),

// Conditional populate Promise
(callback) =>
Outer.find().populate('inners').exec()
.then(outers =>
Promise.all(
outers.map( outer =>
new Promise((resolve,reject) => {
Promise.all(
outer.inners.map( inner =>
(inner.populate)
? Inner.populate(inner,{ path: 'subs' })
: inner
)
).then(inners => {
outer.inners = inners;
resolve(outer)
})
.catch(reject)
})
)
)
)
.then(outers => {
log(outers);
callback();
})
.catch(err => callback(err))


],
(err) => {
if (err) throw err;
mongoose.disconnect();
}
);

这会产生显示“条件”选择的输出,当然可以使用任何一种方法:

Mongoose: subs.remove({}, {})
Mongoose: inners.remove({}, {})
Mongoose: outers.remove({}, {})
Mongoose: subs.insert({ label: '1', _id: ObjectId("5961830256bf9e2d0fcf13b3"), __v: 0 })
Mongoose: subs.insert({ label: '2', _id: ObjectId("5961830256bf9e2d0fcf13b4"), __v: 0 })
Mongoose: subs.insert({ label: '3', _id: ObjectId("5961830256bf9e2d0fcf13b5"), __v: 0 })
Mongoose: subs.insert({ label: '4', _id: ObjectId("5961830256bf9e2d0fcf13b6"), __v: 0 })
Mongoose: inners.insert({ name: '0', populate: false, _id: ObjectId("5961830256bf9e2d0fcf13b7"), subs: [ ObjectId("5961830256bf9e2d0fcf13b3"), ObjectId("5961830256bf9e2d0fcf13b4") ], __v: 0 })
Mongoose: inners.insert({ name: '2', populate: true, _id: ObjectId("5961830256bf9e2d0fcf13b8"), subs: [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ], __v: 0 })
Mongoose: outers.insert({ title: '1', _id: ObjectId("5961830256bf9e2d0fcf13b9"), inners: [ ObjectId("5961830256bf9e2d0fcf13b7") ], __v: 0 })
Mongoose: outers.insert({ title: '2', _id: ObjectId("5961830256bf9e2d0fcf13ba"), inners: [ ObjectId("5961830256bf9e2d0fcf13b8") ], __v: 0 })
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
{
"_id": "5961830256bf9e2d0fcf13b9",
"title": "1",
"__v": 0,
"inners": [
{
"_id": "5961830256bf9e2d0fcf13b7",
"name": "0",
"populate": false,
"__v": 0,
"subs": [
"5961830256bf9e2d0fcf13b3",
"5961830256bf9e2d0fcf13b4"
]
}
]
},
{
"_id": "5961830256bf9e2d0fcf13ba",
"title": "2",
"__v": 0,
"inners": [
{
"_id": "5961830256bf9e2d0fcf13b8",
"name": "2",
"populate": true,
"__v": 0,
"subs": [
{
"_id": "5961830256bf9e2d0fcf13b5",
"label": "3",
"__v": 0
},
{
"_id": "5961830256bf9e2d0fcf13b6",
"label": "4",
"__v": 0
}
]
}
]
}
]
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
{
"_id": "5961830256bf9e2d0fcf13b9",
"title": "1",
"__v": 0,
"inners": [
{
"_id": "5961830256bf9e2d0fcf13b7",
"name": "0",
"populate": false,
"__v": 0,
"subs": [
"5961830256bf9e2d0fcf13b3",
"5961830256bf9e2d0fcf13b4"
]
}
]
},
{
"_id": "5961830256bf9e2d0fcf13ba",
"title": "2",
"__v": 0,
"inners": [
{
"_id": "5961830256bf9e2d0fcf13b8",
"name": "2",
"populate": true,
"__v": 0,
"subs": [
{
"_id": "5961830256bf9e2d0fcf13b5",
"label": "3",
"__v": 0
},
{
"_id": "5961830256bf9e2d0fcf13b6",
"label": "4",
"__v": 0
}
]
}
]
}
]

因此您可以看到,以几乎相同的方式有一个“ bool ”字段正在被测试以确定是执行 .populate() 还是只返回纯数据。

关于javascript - 仅在满足条件时填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com