【问题标题】:Sort Keys in Response Object from Mongoose in ExpressJS and NodeJSExpressJS 和 NodeJS 中 Mongoose 的响应对象中的排序键
【发布时间】:2019-01-24 23:05:41
【问题描述】:

我一直在开发自己的小型 API,到目前为止一切都很好,我只是有一个小问题,我似乎找不到答案。

我在猫鼬中定义了一个这样的模式:

const ArtistSchema = new Schema({
stageName: {
    type: String,
    unique: true,
    required: true,
    minlength: 3,
    maxlength: 255
},
realName: {
    type: String,
    unique: true,
    required: true,
    minlength: 5,
    maxlength: 255
},
birthday: {
    type: Date,
    required: true
},
debutDate: {
    type: Date,
    required: true
},
company: {
    type: String,
    minlength: 5,
    maxlength: 255,
    required: function () {
        return this.active;
    }
},
active: {
    type: Boolean,
    default: true
},
music: [AlbumSchema],
createdAt: {
    type: Date,
    default: Date.now
}
});

我可以在数据库中创建一个条目,也没有问题。我在 app.post 上使用这个功能

    create(req, res, next) {
    const artistProps = req.body;
        Artist.create(artistProps)
            .then(artist => res.send(artist))
            .catch(next);
   },

这很好用,但是 res.send(artist)) 实际上返回的对象没有键顺序.. 或者我无法识别的模式。我希望响应与我在架构中定义的排序相同,因为现在它返回它:

活跃、艺名、实名、厂牌、音乐、生日

虽然应该是艺名、实名、生日、出道日期等。

我希望有人可以在这里帮助我。我知道我可以使用 sort 对特定键的 VALUE 进行排序(如按字母顺序排序 stageName),但我真的找不到任何键。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    Express 的res.send 方法识别出artist 是一个Object,并在其上调用JSON.stringify 以在发送前将Object 转换为JSON 字符串。稍微简化一下,JSON.stringify 方法按创建顺序遍历您的 artist 对象键。 (Here's a link to the more complicated ordering explanation.) 这解释了当前的行为。

    其他人可能会提出自己的建议,告诉你如何实现你的目标,但首先要尝试一个简单的建议:

    • 首先,自己的 JSON.stringify, using a "replacer" to create the output order that you want:

      const artistString = JSON.stringify(artist, ["realName", "stageName", ...])
      // '{"realName": "Paul David Hewson", "stageName": "Bono", ...}'
      
    • 然后,使用res.json(artistString),而不是res.send,发送带有 正确的 Content-Type 标头。 (res.send 会假设你想要 Content-Type: “text/html”.)

    肯定有更复杂的方法,包括创建一个获取键、对其进行排序并返回替换器的函数;或编写您自己的.toJSON() 替代JSON.stringify。您可能需要实现其中一种方法,因为您有嵌套对象; the behavior of the replacer can be a bit wonky in this case。您也许可以在父级之后立即列出嵌套属性,例如:

    ["realName", "type", ...]
    

    但是由于您对某些嵌套属性具有相同的名称,因此这可能对您有用,也可能不适用。您可能必须先将内部字符串化,然后再将外部字符串化(啊!)。

    无论如何,希望我的建议可以成为第一步。

    【讨论】:

    • Ty :) 这实际上是我所希望的......可悲的是它唯一的 hacky :( 比你好多了
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 2019-02-01
    • 2015-08-11
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2016-06-09
    • 2015-06-19
    相关资源
    最近更新 更多