【问题标题】:express.js mongoose populate 2 modelexpress.js 猫鼬填充 2 模型
【发布时间】:2021-05-16 08:46:52
【问题描述】:

我想加入集合 mongoDB,但我在项目中有 2 个模型。

ADMINDETAIL 和 ADMINDETAIL 从 member.model.js 获取 UID。

我如何填充它。

queue.model.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var queueSchema = Schema(
{
    QUEUE: String,
    UID: String,
    DATETIME: String,
    ADMIN_ID: String,
    USERDETAIL:{
        type: Schema.Types.String, 
        ref:"MEMBER"
    },
    ADMINDETAIL:{
      type: Schema.Types.String,
      ref:"MEMBER"
    },
  },
  {
    collection: "QUEUE"
  }
);
var QUEUE = mongoose.model("QUEUE", queueSchema);
module.exports = QUEUE;

member.model.js

var mongoose = require("mongoose");
var memberSchema = mongoose.Schema(
  {
    UID: {type: String},
    NAME: {type: String},
    SURNAME: {type: String},
    IDNUMBER: {type: String},
    PHONE: {type: String},
    ADDRESS: {type: String},
  },
  {
    collection: "MEMBER"
  }
);
var MEMBER = mongoose.model("MEMBER", memberSchema);
module.exports = MEMBER;

queue.router.js

// GET QUEUE BY USER
router.get("/byuid/:UID", (req, res) => {
  var {UID} = req.params;
  Queue.find({UID})
        .populate({Path:"USERDETAIL",model:"MEMBER"})
        .populate({Path:"ADMINDETAIL",model:"MEMBER"})
        .exec((err, data) => {
          if (err) return res.status(400).send(err);
          return res.status(200).send(data);
        });
});

我遇到了错误。

TypeError: utils.populate: invalid path. Expected string. Got typeof `object`

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-populate


    【解决方案1】:

    将字段类型从 String 更改为 ObjectId,如下所示:

     USERDETAIL:{
            type: Schema.Types.ObjectId , 
            ref:"MEMBER"
        },
        ADMINDETAIL:{
          type: Schema.Types.ObjectId ,
          ref:"MEMBER"
        },
      },
    

    添加你的新数据之后,你可以喜欢这样的人口:

    .populate("USERDETAIL ADMINDETAIL")
    

    .populate([{
        path: 'USERDETAIL ',
        model: 'MEMBER'
    }, {
        path: 'ADMINDETAIL',
        model: 'MEMBER'
    }])
    

    我认为你错过了[]

    【讨论】:

    • It error "TypeError: utils.populate: invalid path. Expected string. Got typeof object" 我理解 TypeError。
    • 有了我的回答,还有错误吗?
    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 2021-12-25
    • 2021-06-29
    • 2019-05-04
    • 2015-07-13
    • 2016-10-10
    • 2015-06-20
    相关资源
    最近更新 更多