猫鼬的填充物使田野空



我有两个模式:

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 S。有什么问题?

更新:这是我的查询:

models.Category
            .findOne({_id: req.params.categoryId})
            .populate('tags')
            .then(category => {
                console.log(category);
                res.send(category.tags);
            });

类别架构:

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);
  });

我认为您需要将category.tags的模式定义更改为:

tags: [{ 
    type: Schema.Types.ObjectId,
    ref: 'Tag'
}]

最新更新