mongodb 使用引用打破mongoose模型- Node.js

soat7uwm  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(135)

演唱会模型:

const mongoose = require('mongoose');

const concertSchema = new mongoose.Schema({
  performer: { type: String, required: true },
  genre: { type: String, required: true },
  price: { type: Number, required: true },
  day: { type: Number, required: true },
  image: { type: String, required: true },
  workshops: [{ type: mongoose.Schema.ObjectId, ref: 'Workshop' }]
});

module.exports = mongoose.model('Concert', concertSchema);

字符串
车间型号:

const mongoose = require('mongoose');

const workshopSchema = new mongoose.Schema({
  name: { type: String, required: true },
  concertId: { type: String, required: true, }
});

module.exports = mongoose.model('Workshop', workshopSchema)


演唱会数据示例:

{"_id":{"$oid":"652ff8c9474981f1b2c335ca"},"id":{"$numberInt":"2"},"performer":"Rebekah Parker","genre":"R&B","price":{"$numberInt":"25"},"day":{"$numberInt":"2"},"image":"/img/uploads/2f342s4fsdg.jpg","workshops":[{"$oid":"6538f7023ebd4e3eea6c394d"},{"$oid":"6538f9803ebd4e3eea6c3958"},{"$oid":"6538f9ca3ebd4e3eea6c395a"},{"$oid":"6538fa103ebd4e3eea6c395c"}]}


当我尝试使用await Concert.find().populate('workshops')时,我得到内部服务器错误。如果我不使用.populate('workshops'),那么一切正常。如果我将此行workshops: [{ type: mongoose.Schema.ObjectId, ref: 'Workshop' }]更改为仅使用type: String,则返回concerns集合,但忽略workshops属性。我真的不知道哪里出错了。数组中的workshops ID是有效的,并且在workshops集合中有相应的数据

to94eoyn

to94eoyn1#

您的schema看起来很好,workshops数组的示例数据看起来很典型。很可能您的Model没有注册。请尝试使用populate请求传递Model:

const concert = await Concert.find().populate({ 
   path: 'workshops',
   model: Workshop
});

字符串

相关问题