假設我有以下兩個模式:
const mongoose = require('mongoose')。
const Schema = mongoose.Schema;
const schemaA = new Schema({
tag: [
{
type: mongoose.Schema.Types.ObjectId。
ref。'schemaB',
},
],
});
module.exports = SchemaA = mongoose。 model('schemaA', schemaA) 。
const mongoose = require('mongoose') 。
const Schema = mongoose.Schema;
const schemaB = new Schema({
name: {
type: String,
}
});
module.exports = SchemaB = mongoose. model('schemaB', schemaB) 。
我怎樣才能在SchemaA中找到所有其tag欄位與SchemaB名稱相匹配的檔案呢?
我知道,如果我有SchemaB的_id,我就可以這樣做了,
const schemaBId = 'some-_id-string'/span>
const docs = await SchemaA.find({ tag: schemaBId })
但是,如果我只有name值,我怎么能做到這一點呢?
uj5u.com熱心網友回復:
你可以嘗試使用mongoose populate()函式,它可能會幫助你實作你想要的東西。這里是populate docs,供快速參考。
uj5u.com熱心網友回復:
首先使用查找功能獲得ModelB的資料,然后將這些資料作為t,之后使用匹配查詢,找到ModelB的名字是test
ModelA.aggregate([
{
$lookup: {
from: 'collectionB',
localField: 'tag',
foreignField: '_id',
as: 't'。
},
},
{
$match: { 't.name'/span>: 'test' },
},
]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319849.html
標籤:
