使用Mongoose在MongoDB中保存文档时如何保留字段的顺序?

时间:2016-07-05 15:11:05

标签: node.js mongodb mongoose mongoose-schema

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

{ 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)的结果。

1 个答案:

答案 0 :(得分:0)

不确定这不是错误。但您可以在presave hook中重新组合位置:

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

  next();
});

希望这有帮助。