简体   繁体   中英

express.js mongoose populate 2 model

I'm want to join collection mongoDB but I've 2 model in project.

ADMINDETAIL and ADMINDETAIL get UID from member.model.js.

How I populate that.

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

Error I got.

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

change the type of filed from String to ObjectId like this:

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

add your new data after that you can like this for population:

.populate("USERDETAIL ADMINDETAIL")

or

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

I think you are missing []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM