【问题标题】:How to order responses in Mongoose?如何在猫鼬中订购响应?
【发布时间】:2020-08-19 03:30:03
【问题描述】:

从我的数据库中检索数据时,Schema 的顺序没有得到维护,并且响应不是我需要的格式。我需要响应与 Schema 相同,我得到的响应是这样的:

响应

[
 {
  "comments": [],
  "_id": "5ede3608c9cd033744641188",
  "title": "Book 1",
  "__v": 0
 },
 {
  "comments": [],
  "_id": "5ede360cc9cd033744641189",
  "title": "Book 2",
  "__v": 0
 }
]

图书架构:

const bookSchema = new mongoose.Schema({
    title: String,
    commentCount: Number,
    comments: [String]
  }, {collection: 'fcclibrary'});

  const Book = mongoose.model('Book', bookSchema);

POST 请求

.post(function (req, res){
      let title = req.body.title;
      let newBook = new Book({
        title: title
      });
      newBook.save((err, book) => {
        if(err) {
          console.log(err);
        } else {
          console.log(book);
          res.json({title: book.title, id: book.id});
        }
      })
    })

GET 请求

app.route('/api/books')
    .get(function (req, res){
      Book.find({}, (err, found) => {
        if(err) {
          console.log(err);
        } else {
          console.log(found);
          res.json(found);
        }
      })

从数据库中检索架构时如何保持架构的顺序?我已经尝试过retainKeyOrder: true

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    首先确保您使用的是 Mongoose 4.6.4 或更高版本 (Mongoose docs) 奇怪的是,retainKeyOrder 对你不起作用(我自己从未尝试过,但请仔细检查)

    此外,这里还有一些 StackOverflow 帖子讨论了与您的案例非常相似的案例:

    Sort Keys in Response Object from Mongoose in ExpressJS and NodeJS

    Using a "replacer" to create the output order that you want

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 2017-08-31
      • 1970-01-01
      • 2016-05-05
      • 2017-09-13
      • 2021-09-28
      • 2018-12-29
      • 1970-01-01
      • 2017-08-26
      相关资源
      最近更新 更多