是否有可能填充没有' _id '

Is it possible to populate without `_id`?

本文关键字:id 有可能 填充 是否      更新时间:2023-09-26

我手动设置一个uid到我的藏品…我想知道我是否有可能使用uid来填充?我不想使用'_id',因为在我的数据库中有很多集合,应该改变很多东西…像这样:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
    var PersonSchema = new Schema({
        name    : String
      , age     : Number
      , stories : [{ type: String, ref: 'Story' }]
    });
    var StorySchema = new Schema({
        _creator : { type: String, ref: 'Person' }
      , title    : String
      , fans     : [{ type: String, ref: 'Person' }]
    });
    var Story  = mongoose.model('Story', StorySchema);
    var Person = mongoose.model('Person', PersonSchema);

不,没有'_id'的mongodb文档是不可能的,如果你想避免重复id,你可以在保存文档之前将uid放在'_id'中。如果您单独保留uid, '_id'将自动填充为ObjectId。

下面是如何做到这一点的一个清楚的例子(https://mongoosejs.com/docs/populate.html):

Story.
  find(...).
  populate({
    path: 'fans',
    select: 'name -_id' // <---------------'-_id' exclude _id field.
  }).
  exec();