我有两个模式:
const categorySchema = Schema({
slug: {
type: String,
index: true
},
tags: {
type: [Schema.Types.ObjectId],
ref: 'Tag'
}
});
和
const tagSchema = Schema({
title: String,
type: {
type: String,
enum: ['bool', 'selectable', 'int']
},
categories: [{
type: Schema.Types.ObjectId,
ref: 'Category'
}],
possibleValues: [String]
});
现在问题就在于此。当我尝试使用标签填充我的类别实例时,整个字段变为空数组,而当没有.populate()
语句时,那里有一些ObjectId
。有什么问题?
更新:这是我的查询:
models.Category
.findOne({_id: req.params.categoryId})
.populate('tags')
.then(category => {
console.log(category);
res.send(category.tags);
});
答案 0 :(得分:1)
我认为您需要将category.tags
的架构定义更改为:
tags: [{
type: Schema.Types.ObjectId,
ref: 'Tag'
}]
答案 1 :(得分:1)
类别架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = Schema({
slug: {type: String,index: true},
tags: { type: [Schema.Types.ObjectId],ref: 'Tag'}
},{
collection:'categories'
});
var Category = mongoose.model('Category', categorySchema);
标记架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var tagSchema = Schema({
title: String,
type: {
type: String,
enum: ['bool', 'selectable', 'int']
},
categories: [{
type: Schema.Types.ObjectId,
ref: 'Category'
}],
possibleValues: [String]
},{
collection:'tags'
});
var Tag = mongoose.model('Tag', tagSchema);
查询查询:
Category.
findOne({_id: req.params.categoryId}).
populate('tags').
exec(function (err, categories) {
return res.json(categories);
});