在ExpressJS和NodeJS中从Mongoose中对响应对象中的键进行排序

时间:2018-08-17 21:49:55

标签: node.js mongodb express mongoose

我一直在使用自己的小型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))实际上返回没有键顺序的对象..或以我无法识别的模式。我希望响应与我在架构中定义的排序相同,因为现在它返回它:

活动,艺名,实名,标签,音乐,生日

应为舞台名称,真实姓名,生日,beautyDate等。

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

1 个答案:

答案 0 :(得分:0)

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

其他人可能会针对自己的目标提出自己的建议,但是这里有一个简单的建议:

  • 首先,做一个自己的 JSON.stringifyusing 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)将JSON字符串与 正确的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", ...]

但是由于某些嵌套属性的名称相同,因此这可能对您不起作用。在对外部进行字符串化之前,您可能必须对内部进行字符串化(gah!)。

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