不能向(猫鼬)对象添加额外的元素

毫升

我有一个带有 api 的 nodejs express 应用程序,用于从 mongodb 数据库返回数据。这是我的猫鼬模型:

const bookingSchema = new mongoose.Schema({
  timestamp: {
    type: Date,
    default: Date.now,
    required: true
  },
  tags: {
    type: [String],
    required: true
  },
  amount: {
    type: Number,
    required: true
  },
  type: {
    type: String,
    required: true,
    enum: ['expense', 'income']
  }
})

当我使用路径调用 api 时,/api/bookings/listbymonth/2019/1会调用后端内的此函数:

const bookingsListByMonth = (req, res) => {
  const year = ("0000" + req.params.year).slice(-4)
  const month = ("0000" + req.params.month).slice(-2)
  const dateOfMonth = `${year}${month}01`
  const start = moment(dateOfMonth).startOf("month")
  const end = moment(dateOfMonth).endOf("month")

  bookingMongooseModel
    .find({
      timestamp: {
        $gt: start,
        $lt: end
      }
    })
    .sort({ timestamp: 1 })
    .exec((err, bookings) => {
      if (!bookings) {
        return res
          .status(404)
          .json({
            "message": "booking not found"
          })
      } else if (err) {
        return res
          .status(404)
          .json(err)
      }
      res
        .status(200)
        .json(processBookings(bookings));
    })
}

我不想简单地返回 json 数据,而是想预处理数据并制作一个不错的时间戳和货币字段。这就是 json 数据通过一个附加processBookings函数运行的原因为了测试,我尝试添加另一个字段timestamp2: 123

const processBookings = (bookings) => {
  console.log("Bookings unsorted: \n" + bookings + "\n")

  const mainTags = [
    "Essen",
    "Essen gehen",
    "Notwendiges",
    "Luxus",
  ]

  let bookingsProcessed = []

  mainTags.forEach((tag) => {
    let singleTagBookings = bookings.filter(
      booking => booking.tags.includes(tag)
    )

    singleTagBookings.map((item) => {
      item.timestamp2 = "123"
      return item
    })

    let message = null;
    if (singleTagBookings.length === 0) {
      message = "No bookings found";
    }

    bookingsProcessed.push({
      name: tag,
      bookings: singleTagBookings,
      message: message
    })
  });

  console.log("Bookings sorted:")
  bookingsProcessed.forEach((item) => {
    console.log(item)
  })

  return bookingsProcessed
}

bookings数组中的对象应该有另一个属性timestamp2: "123",但它们没有。这是输出:

Bookings unsorted: 
{ tags: [ 'Luxus', 'voluptatem', 'atque', 'qui', 'sunt' ],
  _id: 5cb2c9e1ff6c9c6bef95f56f,
  timestamp: 2019-01-06T08:53:06.945Z,
  amount: 68.02,
  type: 'expense',
  __v: 0 },{ tags: [ 'Essen gehen', 'ut', 'unde', 'et', 'officiis' ],
  _id: 5cb2c9e1ff6c9c6bef95f56e,
  timestamp: 2019-01-09T20:35:06.411Z,
  amount: 33.77,
  type: 'income',
  __v: 0 }

Bookings sorted:     
{ name: 'Essen', bookings: [], message: 'No bookings found' }
{ name: 'Essen gehen',
  bookings: 
   [ { tags: [Array],
       _id: 5cb2c9e1ff6c9c6bef95f56e,
       timestamp: 2019-01-09T20:35:06.411Z,
       amount: 33.77,
       type: 'income',
       __v: 0 } ],
  message: null }
{ name: 'Notwendiges',
  bookings: [],
  message: 'No bookings found' }
{ name: 'Luxus',
  bookings: 
   [ { tags: [Array],
       _id: 5cb2c9e1ff6c9c6bef95f56f,
       timestamp: 2019-01-06T08:53:06.945Z,
       amount: 68.02,
       type: 'expense',
       __v: 0 } ],
  message: null }

正如评论中所建议的那样,我尝试将其let bookings = [ {tags: ["Essen"]}];用作测试数据。在这里它有效。输出是:

Bookings unsorted: 
[object Object]

Bookings sorted:
{ name: 'Essen',
  bookings: [ { tags: [Array], timestamp2: '123' } ],
  message: null }
{ name: 'Essen gehen',
  bookings: [],
  message: 'No bookings found' }
{ name: 'Notwendiges',
  bookings: [],
  message: 'No bookings found' }
{ name: 'Luxus', bookings: [], message: 'No bookings found' }

所以我想这与我的猫鼬模型限制添加任何其他字段有关。但是如果我把

console.log("EXTENSIBLE " + Object.isExtensible(bookings))
res
  .status(200)
  .json(processBookings(bookings));

进入我的bookingsListByMonth功能,我得到:

EXTENSIBLE true

所以理论上我应该能够向bookings对象添加一些东西

作为一种解决方法,我将该timestamp2字段添加到我的猫鼬模型中:

const bookingSchema = new mongoose.Schema({
  timestamp: {
    type: Date,
    default: Date.now,
    required: true
  },
  timestamp2: {
    type: String,
    default: null
  },
  tags: {
    type: [String],
    required: true
  },
  amount: {
    type: Number,
    required: true
  },
  type: {
    type: String,
    required: true,
    enum: ['expense', 'income']
  }
})

这有效,但是它在我的数据库中添加了一个额外的无用数据字段。如何修改bookings从 mongodb 返回json 对象?如果因为它是猫鼬模型而无法修改它,我该如何制作可编辑的副本?

苏达山德瓦尔

从查询返回的文档是限制添加新字段的猫鼬文档。为了将 mongoose 文档转换为纯 JavaScript 对象,mongoose 中有一个方法/选项- https://mongoosejs.com/docs/tutorials/lean.html

查找查询看起来像这样

bookingMongooseModel
.find({
  timestamp: {
    $gt: start,
    $lt: end
  }
})
.sort({ timestamp: 1 })
.lean()

此外,mongoose 提供了可配置的选项供您在定义架构时进行设置。例如, new Schema({..}, {timestamps: true}); 将在您的文档 createdAt 和 updatedAt 中创建两个字段。有关更多信息,请参阅此处的选项部分https://mongoosejs.com/docs/guide.html#options

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

猫鼬-向回调中返回的对象添加方法

来自分类Dev

无法在猫鼬函数中向对象添加属性

来自分类Dev

在猫鼬中向具有变量名称的对象添加新属性

来自分类Dev

猫鼬:如何向.select()添加过滤器

来自分类Dev

为什么不能删除猫鼬模型的对象属性?

来自分类Dev

更新猫鼬对象

来自分类Dev

遍历猫鼬对象

来自分类Dev

猫鼬对象关系

来自分类Dev

猫鼬架构与对象

来自分类Dev

在猫鼬模型中添加到“人口”对象

来自分类Dev

猫鼬-这个额外的_id属性被添加到我的友谊属性中是什么?

来自分类Dev

猫鼬从当前元素排序

来自分类Dev

无法使用非猫鼬对象的猫鼬对象方法

来自分类Dev

猫鼬填充与对象嵌套

来自分类Dev

猫鼬参考对象找到

来自分类Dev

猫鼬填充对象数组

来自分类Dev

猫鼬验证对象结构

来自分类Dev

在R中,如何向表对象添加额外的列?

来自分类Dev

Axios帖子向对象添加了额外的键

来自分类Dev

猫鼬,向集合的一组文档中添加/更新数据

来自分类Dev

如何使用猫鼬向数据库添加动态输入名称?

来自分类Dev

当我循环它时,猫鼬查找结果不能用作对象

来自分类Dev

猫鼬查询结果不能与数据对象一起导出

来自分类Dev

猫鼬,MongoDb,节点。猫鼬对象未注册find()

来自分类Dev

向多维对象添加元素?

来自分类Dev

不能在猫鼬中使用诺言

来自分类Dev

猫鼬不能使用双引号?

来自分类Dev

不能在猫鼬中使用诺言

来自分类Dev

猫鼬找到对象成对象数组