我有 2 个模式。
organization Schema
和 inventory schema
组织架构是这样的
const mongoose = require("mongoose");
const organizationSchema = new mongoose.Schema({
organizationName: {
type: String,
required: true,
},
});
organizationSchema.virtual("inventories", {
ref: "Inventory",
// Localfield is user id
localField: "_id",
// forefield is owner field in task
foreignField: "owner",
});
organizationSchema.virtual("user", {
ref: "User",
localField: "_id",
foreignField: "organizationId",
});
const Organization = mongoose.model("Organization", organizationSchema);
库存架构是这样的
const inventorySchema = new mongoose.Schema({
inventoryName: {
type: String,
required: true,
},
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Organization'
},
users: [{ type: ObjectId, ref: "User" }],
});
inventorySchema.virtual("items", {
ref: "Item",
localField: "_id",
foreignField: "inventoryId",
});
const Inventory = mongoose.model("Inventory", inventorySchema);
所以在api路径中。我想获取与某个组织相关的所有库存。 所以我就是这样填充的。但我只取回没有填充数据的组织。
我在这里做错了什么?
router.get("/organizations/:orgId/inventory", auth, async (req, res) => {
try {
let organization = await Organization.findOne({
_id: req.params.orgId,
}).populate('user')
res.send(organization)
} catch (err) {
return res.status(404).send({ error: "Organization not found" });
}
});
我正在调用的API
{{url}}/organizations/65ec63bee52ddf849fe70f76/inventory
首先,您的代码尝试填充
user
而不是 inventories
,因此您需要将代码更改为:
const organization = await Organization.findOne({
_id: req.params.orgId,
}).populate('inventories');
其次,当您使用express
res.send()
方法时,传递给此方法的参数可以是多种不同类型之一,例如String
、Array
、Object
等。Express将使用参数类型来确定哪个 Content-Type
在响应标头中设置。在您的情况下,您要发送一个对象,因此 Express 会将其设置为 Content-Type: application/json
。
理解这一点很重要,因为当数据传递到
toJSON()
和 toObject()
时,不包括猫鼬虚拟。由于 inventories
是虚拟的,因此不会在数据中输出。您可以通过在架构中设置选项来解决此问题:
const organizationSchema = new mongoose.Schema({
organizationName: {
type: String,
required: true,
},
},{
toJSON: { virtuals: true },
toObject: { virtuals: true }
});