【问题标题】:Mongoose Populate a fieldMongoose 填充字段
【发布时间】:2017-05-21 15:36:54
【问题描述】:

我有两个猫鼬模式

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var itemSchema = new Schema({

    name: {type: String, required: true, max: 25, trim: true},
    price: {type: Number, required: true, trim: true, default: 0},
    tax: {
        type: Schema.Types.ObjectId,
        ref: "Store"
    }
});

module.exports = mongoose.model('Item', itemSchema);

第二个架构

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var storeSchema = new Schema({
    name: {type: String, required: true, trim: true},
    taxes: [
        {
            name: String,
            rate: Number
        }
    ]
});

module.exports = mongoose.model('Store', storeSchema);

我想要做的是用对象的 storeSchema 税收数组填充 itemSchema 税收对象。每次我将一个新的税收对象推送到税收数组时,猫鼬都会创建一个 ObjectId。我将该 ObjectId 存储在我的 itemSchema Tax 中。我想使用该 _id 来检索与 itemSchema _id 匹配的商店税。

到目前为止我已经尝试过了,但我在 tax 属性中没有得到任何结果。

Item.find().populate("tax", "taxes").exec(function (err, docs) {
        if (err) return console.error(err);
        console.log(items);
    });

【问题讨论】:

  • 您面临的问题是什么?
  • 我在税务字段中得到空值。
  • 其他一切都好吗??
  • 是的,我得到了其他一切。
  • 我又看了一遍这个问题,我之前理解错了。您正在尝试使用子文档 ObjectId 进行填充,这是不可能的。这就是你得到 null 的原因。

标签: mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

试试这个查询

Item.find().populate({
    path: 'tax',
    select: 'taxes'
}).exec(function (err, docs) {
    if (err) {
        console.error(err);
    } else {
        console.log(docs);
    }
});

【讨论】:

    【解决方案2】:

    使用Item.find().populate("Store", "taxes") 代替Item.find().populate("tax", "taxes")

    【讨论】:

      【解决方案3】:
      Item.find().populate(path:"tax", model: )
      

      提及您的项目模型文件名...不要使用""'' 作为文件名,只需添加文件名即可。

      【讨论】:

        猜你喜欢
        • 2012-01-22
        • 2013-07-06
        • 2021-09-06
        • 1970-01-01
        • 1970-01-01
        • 2015-09-19
        • 2019-01-01
        • 2018-12-28
        • 2021-11-03
        相关资源
        最近更新 更多