【问题标题】:Mongoose populate a field without ObjectId?Mongoose 填充没有 ObjectId 的字段?
【发布时间】:2017-12-09 04:20:33
【问题描述】:

我有一个架构:

var Schema = mongoose.Schema;

var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
    externalId: String,
    price: Number,
    quantity: {
        type: Number,
        default: 1
    },
    comment: {
        type: String,
        default: '',
        trim: true
    },
    entity: {
        type: String,
        ref: 'Entity'
    }
}],
tableId: String
});

mongoose.model('Ticket', TicketSchema);

我想用 ObjectId 以外的唯一字段填充实体字段。 我怎样才能做到这一点?

【问题讨论】:

  • 这个包可能对npmjs.com/package/mongoose-auto-increment有帮助,它将使用_id中的数字类型,从0,1 ++开始,而不是ObjectId
  • @p0k8_ 我不是这个意思。我已经有了一个独特的领域。但它不是_id。那么,如何使用此字段填充猫鼬模型?
  • 您可以像使用 ObjectId 一样实现这一目标。根据 mongoose valids refs 可以是ObjectId, Number, String, and Buffer。只是您所引用的集合应该具有该引用值作为其_id 字段。

标签: node.js mongoose populate


【解决方案1】:

虽然回答迟了。请检查 Populate Virtuals for Mongoose 4.5.0

点击下方链接

http://mongoosejs.com/docs/populate.html

向下滚动或搜索 Populate Virtuals,您会看到它完全符合您的要求。

【讨论】:

    【解决方案2】:

    我发现 Views 是一种有用的方法,但不确定它是否最有效!例如,在movielens数据库中,我想使用'movieId'作为外键,将评级集合中的'movieId'引用到电影集合中的'movieId'。

    db.createView('rating-movie-view','ratings',[{$lookup:{from:"movies",localField:"movieId",foreignField:"movieId",as:"ratings_movie"}},{ $project:{'userId':1,'movieId':1,'rating':1,'timestamp':1,'ratings_movie.title':1,'ratings_movie.genres':1 } }])
    

    由此创建的新视图“rating-movie-view”具有必填字段“title”和“genres”。

    db["rating-movie-view"].findOne()
    
    {
        "_id" : ObjectId("598747c28198f78eef1de7a3"),
        "userId" : 1,
        "movieId" : 1129,
        "rating" : 2,
        "timestamp" : 1260759185,
        "ratings_movie" : [
            {
                "title" : "Escape from New York (1981)",
                "genres" : "Action|Adventure|Sci-Fi|Thriller"
            }
        ]
    }
    

    希望这有用!

    这里不熟悉movielens数据的都是schema

    var MovieSchema = new mongoose.Schema({
      movieId: Number,
      title: String,
      genres: String,
    });
    
    var RatingSchema = new mongoose.Schema({
      userid: Number,
      movieId:Number,
      rating: Number,
      timestamp:Number,
    });
    

    //查看架构

    var RatingViewSchema = new mongoose.Schema({
      userid: Number,
      movieId:Number,
      rating: Number,
      timestamp:Number,
      rating_movie:{title:String,genres:String}
    });
    

    【讨论】:

      【解决方案3】:

      我不确定我是否正确理解了您的问题。

      在 Mongoose 模型中,如果我们不指定主键,它会自动添加一个名为 ObjectId 的额外字段,并为每个对象分配一个唯一值。

      如果我们需要指定自己的密钥,我们可以通过指定 key 属性来实现。

      例如:

      mongoose.model('Todo', {
        todoID: {
          type: String,
          key: true
        },
        text: {
          type: 'text'
        },
        done: {
          type: Boolean,
          default: false,
        },
        date: {
          type: Date,
        },
        items: [{
          entity: {
            type: String,
            ref: 'Entity'
          }
        }]
      });
      

      我希望,这就是你的意思。

      如果您询问基于 Items -> 实体的属性获取对象,

      Todo.find({'items.entity.type':required_type}, function(err, foundTodos){
            // ---
         });
      

      谢谢,

      【讨论】:

      • 我不想使用“查找”查询。我只想通过一个不是 ObjectID 但它是唯一的字段来填充“实体”。
      【解决方案4】:

      使用 crypto 对像 objectId 之类的唯一内容进行哈希处理,然后将其保存到您的实体中。

      Var hash = crypto.createHmac('sha256', ticket.objectId).digest('hex');
      

      Ticket.entities=哈希;

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 2012-01-22
        • 2021-03-03
        • 2017-11-05
        • 2017-05-21
        • 2017-04-20
        • 1970-01-01
        • 2021-08-25
        • 2013-07-06
        相关资源
        最近更新 更多