Mongoose:使用 _id 以外的字段填充路径

Don*_*ong 7 javascript schema mongoose mongodb node.js

默认情况下,mongoose/mongo 将使用该字段填充路径_id,并且似乎没有办法将其更改_id为其他内容。

这是我的两个以一对多关系连接的模型:

const playlistSchema = new mongoose.Schema({
  externalId: String,
  title: String,
  videos: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Video',
  }],
});

const videoSchema = new mongoose.Schema({
  externalId: String,
  title: String,
});
Run Code Online (Sandbox Code Playgroud)

通常,在查询播放列表时,您videos只需填充.populate('videos'),但在我的例子中,我想使用该externalId字段而不是默认的_id。那可能吗?

Tun*_*mee 8

据我所知,目前使用 mongoose 实现此目的的方法是使用virtuals。填充虚拟时,您可以将localField和指定foreignField 为您想要的任何内容,因此您不再受默认值_idas 的束缚foreignField。有关此的更多详细信息,请参见此处

对于您的问题中描述的场景,您需要向 中添加一个 virtual playerlistSchema,如下所示:

playlistSchema.virtual('videoList', {
  ref: 'Video', // The model to use
  localField: 'videos', // The field in playerListSchema
  foreignField: 'externalId', // The field on videoSchema. This can be whatever you want.
});
Run Code Online (Sandbox Code Playgroud)

现在,每当您查询播放器列表时,您都可以填充videoList虚拟以获取引用的视频文档。

PlaylistModel
  .findOne({
    // ... whatever your find query needs to be
  })
  .populate('videoList')
  .exec(function (error, playList) {
    /* if a playList document is returned */
    playList.videoList; // The would be the populated array of videos
  })
Run Code Online (Sandbox Code Playgroud)