我正在使用 mongo db 'ref' 功能將表中的物件填充到我要回傳的檔案中
這是存盤物件 ID ref 的表
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const StaticAssignmentSchema = new Schema({
affiliation: { type: String },
REF_person: [{ type: Schema.Types.ObjectId, ref: 'users' }],
});
module.exports = StaticAssignmentNew = mongoose.model('staticassignments', StaticAssignmentSchema);
這是我的用戶表架構
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: { type: String },
phone: { type: String },
password: { type: String },
affiliation: { type: String },
timezone: { type: String },
date: { type: Date, default: Date.now },
});
module.exports = User = mongoose.model('users', UserSchema);
這是我從 mongo 獲取資料的方法
var query = { affiliation: affiliation };
var ret = await StaticAssignment.findOne(query).populate('REF_person');
回傳以下內容:
{
"_id": "61a8376154377e5704ae79cf",
"affiliation": "800_800",
"REF_person": [{
"_id": "5e441bd5332359211c0403fb",
"name": "Frank",
"phone": "8008008001",
"password": "$2a$10$T9wYLE3v/n8S4GB.oyYOmCsGUdxXQiOjpiDaG0JGbKy",
"affiliation": "800_800",
"timezone": "America/Los_Angeles",
"date": "2020-02-12T15:37:57.167Z"
}]
}
但是,我想回傳 populate 呼叫的一個子集:
{
"_id": "61a8376154377e5704ae79cf",
"affiliation": "800_800",
"REF_person": [{
"_id": "5e441bd5332359211c0403fb",
"name": "Frank",
"phone": "8008008001",
}]
}
我該怎么做才能回傳子集?
謝謝樓主!
回答:
var query = { affiliation: affiliation };
var ret = await StaticAssignment.findOne(query)
.populate({path: 'REF_person', select: '_id name phone'});
uj5u.com熱心網友回復:
嘗試 var ret = await StaticAssignment.findOne(query).populate({path: 'REF_person', select: 'name phone'});
查看此頁面:https : //www.codegrepper.com/code-examples/whatever/mongoose populate select fields
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371484.html
