【问题标题】:How to use join with MixedId field and another field as ObjectId in Mongoose如何在 Mongoose 中使用 MixedId 字段和另一个字段作为 ObjectId 的连接
【发布时间】:2016-06-30 16:31:50
【问题描述】:

我正在为 2 个模式使用连接,如下所示:-

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CompanySchema = new Schema({
    name: String,
    address: String,
    address2: String,
    url: String,
    geoLat: String,
    geoLon: String,
    telephone: String,
    npi:String,
    active: Boolean,
    tax_id:String,
    businessTypeId:[
        {type: Schema.Types.ObjectId, ref: 'BusinessType'}
    ],
    partners:[{type :Schema.Types.Mixed, ref:'TradingPartners'}]

});

module.exports = mongoose.model('Company', CompanySchema);

架构 2:-

'use strict';

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var TradingPartnersSchema = new Schema({
name: String,
id: String,
enrollment_required: Schema.Types.ObjectId,
supported_transactions: Schema.Types.Mixed,
is_enabled: Boolean,
clearinghouse:String,
last_updated:String

});

module.exports = mongoose.model('TradingPartners', TradingPartnersSchema);

现在我在我的控制器中使用以下代码进行连接,这会引发错误:-

exports.findCompanyById = function(req, res) {

    Company.findById(req.params.id)
      .populate('partners')
      .exec(function (err, company) {
        console.log(company);
        if(err) return res.send(500, err);
        return res.send(204);
      });
};

运行服务后出现以下错误。有人可以帮忙吗?

{"message":"Cast to ObjectId failed for value \"[object Object]\" at path \"_id\"","name":"CastError","type":"ObjectId","value":{"id":"56dfa20249c25b7a3290596e"},"path":"_id"}

【问题讨论】:

  • 根据doc,只有ObjectIdNumberStringBuffer可用作refs

标签: angularjs mongodb mongoose mean


【解决方案1】:

我猜你的 req.params.id 是一个对象控制台日志 req.params.id 并从该对象中查找 id

partners:[{type :Schema.Types.Mixed, ref:'TradingPartners'}] 改为

合作伙伴:[{type :Schema.Types.ObjectId, ref:'TradingPartners'}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多