【问题标题】:How can the order of fields be preserved while saving a document in MongoDB with Mongoose?使用 Mongoose 在 MongoDB 中保存文档时如何保留字段顺序?
【发布时间】:2016-07-05 23:26:03
【问题描述】:

我们正在尝试将位置日志保存在集合中。猫鼬模式定义如下 -

{ user: { type: String, required: true }, location: { longitude: {type: Number}, latitude: type: { type: Number}}

我们通过代码保存位置日志(用法如下)-

Model.findOneAndUpdate({user: 1},
  {location:{longitude: 9.0, latitude: 10.0}},
  function(err) {...});

通过3T MongoChef查询数据库,发现位置对象的保存顺序不一致,导致地理位置索引错误。即使两个用户有相同的位置,我们也只能得到键的排序格式为(latitude, longitude) 的结果。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    不确定这不是错误。但是你可以在presave钩子中重新组装位置:

    schema.pre('save', function(next) {
      this.location = {
        latitude: this.location.latitude,
        longitude: this.location.longitude,
      };
    
      next();
    });
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2013-09-08
      • 2020-01-03
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多