这是第一个型号。它位于名为models / user.js
的文件夹中'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = Schema({
publications: [{
description: String,
categories: [{
type: Schema.Types.ObjectId,
ref: 'Category.subcategories'
}]
}]
模型类别。它位于名为models / category.js
的文件夹中'use strict'
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CategorySchema = Schema({
name: String,
subcategories: [{
name: String
}]
});
看看UserSchema有类别。这个有这个参考:
ref: 'Category.subcategories'
我有一个名为controller的文件夹。下一个json来自controller / category.js
'use strict'
var Categories = require('./models/category');
function getCategories(req, res){
Categories.find({},(err, categories) =>{
if(err){
res.status(500).send({ message: 'Error en la peticion' });
return;
}
if(!categories){
res.status(404).send({ message: 'No hay categories' });
return
}
res.status(200).send({ categories });
});
}
module.exports = {
getCategories
}
类别的json看起来像这样。
{
"categories": [
{
"subcategories": [
{
"_id": "5ae4a8b0a7510e3bd80917db",
"name": "subcategory1"
},
{
"_id": "5ae4a8b0a7510e3bd80917da",
"name": "subcategory2"
},
{
"_id": "5ae4a8b0a7510e3bd80917d9",
"name": "subcategory3"
}
],
"_id": "5ae4a8b0a7510e3bd80917d7",
"name": "Category1",
"__v": 0
},
{
"subcategories": [
{
"_id": "5ae4a8b0a7510e3bd80917e0",
"name": "subcategory1"
},
{
"_id": "5ae4a8b0a7510e3bd80917df",
"name": "subcategory2"
}
],
"_id": "5ae4a8b0a7510e3bd80917dc",
"name": "Category2",
"__v": 0
}
]
}
每个子类别2属于一个类别。
这个位于controller / user.js
中没有填充的用户将看起来像这样
User.find({}, (err, publications) => {
if (err) {
res.status(500).send({
message: "Error en la peticion " + err
});
return;
}
if (!publications) {
res.status(404).send({
message: "Publicacion no encontrada"
});
return;
}
res.status(200).send(publications);
结果
"publications": [
{
"description": "abc",
"categories": [
"5ae4a8b0a7510e3bd80917db",
"5ae4a8b0a7510e3bd80917da"
]
},
{
"description": "abcddvas asa",
"categories": [
"5ae4a8b0a7510e3bd80917e0"
]
},
]
当我这样做时,我需要填充类别。
User.find().populate('publications.categories').then(function (err, posa) {
if (err) {
res.status(500).send(err);
return;
}
res.status(500).send(posa);
return;
});
所以最终的json应该是这样的:
"publications": [
{
"description": "abc",
"categories": [
{
"_id": "5ae4a8b0a7510e3bd80917db",
"name": "subcategory1"
},
{
"_id": "5ae4a8b0a7510e3bd80917da",
"name": "subcategory2"
}
]
},
{
"description": "abcddvas asa",
"categories": [
{
"_id": "5ae4a8b0a7510e3bd80917e0",
"name": "subcategory1"
}
]
},
]
但结果并没有告诉我最后的json。
我看到有一个名为Dynamic References的选项。 http://mongoosejs.com/docs/populate.html
示例显示了这个
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: ObjectId, refPath: 'connections.kind' }
}]
});
使用refPath而不是使用ref。但对我来说并没有那么做。
我试着用这个
https://github.com/buunguyen/mongoose-deep-populate
但这对我没用。
我试着做了很多尝试。没有人适合我。我一直在寻找日子并尝试很多事情,但我无法解决这个问题。