简体   繁体   English

Mongodb:创建嵌入式文档 - 获取 ID

[英]Mongodb: Create embedded document - get Id

I'm trying to implement a simple CRUD Create for an embedded document.我正在尝试为嵌入式文档实现一个简单的 CRUD Create

The URL is like this [POST] /restaurants/:id/subsidiaries网址是这样的[POST] /restaurants/:id/subsidiaries

The query looks like this:查询如下所示:

const restaurant = await Restaurant.findByIdAndUpdate(req.params.id, {
  $push: {
    subsidiaries: {
      phone,
      email,
      title,
      ...
    },
  },
})

I'm using mongoose - so this automatically creates an id for the subsidary.我正在使用猫鼬 - 所以这会自动为子公司创建一个 id。

I now want to return the newly created subsidary (including the ID).我现在想返回新创建的子公司(包括 ID)。 Given that I don't have any other identifier in my data - how can I find which is the newly created document?鉴于我的数据中没有任何其他标识符 - 我如何找到哪个是新创建的文档?

I know that Mongo encourages embedding documents - but I could not find any information about how to handle typical (I find that a very typical case) REST/CRUD problems.我知道 Mongo 鼓励嵌入文档 - 但我找不到任何关于如何处理典型(我发现这是一个非常典型的案例)REST/CRUD 问题的信息。

The answer can be found in the mongodb $push modifiers documentation https://docs.mongodb.com/manual/reference/operator/update/push/#modifiers答案可以在 mongodb $push 修饰符文档https://docs.mongodb.com/manual/reference/operator/update/push/#modifiers 中找到

Without the $position modifier, the $push appends the elements to the end of the array.如果没有 $position 修饰符,$push 会将元素附加到数组的末尾。

So as we know, the added element will be the last one in the returned array of embedded documents.所以我们知道,添加的元素将是返回的嵌入文档数组中的最后一个。

// Question
const restaurant = await Restaurant.findByIdAndUpdate(req.params.id, {
  $push: {
    subsidiaries: {
      phone,
      email,
      title,
      ...
    },
  },
}, { new: true })

// Answer
if (!restaurant) return res.sendStatus(500)

const newlyCreatedSubsidiary = restaurant.subsidiaries.slice(-1)[0]
res.send(newlyCreatedSubsidiary)

Don't forget to wrap this into a try-catch 😉.不要忘记把它包装成一个try-catch 😉。

It is also possible to add the document as the first child into the array (newest first order).也可以将文档作为第一个子元素添加到数组中(最新的第一个顺序)。

We can use $position: 0 to achieve this - but it also requires to put the embedded document into the $each: [] array.我们可以使用$position: 0来实现这一点 - 但它也需要将嵌入的文档放入$each: []数组中。

There's the code:有代码:

const restaurant = await Restaurant.findByIdAndUpdate(
  req.params.id,
  {
    $push: {
      subsidiaries: {
        $each: [
          {
            phone,
            email,
            title,
            ...
          },
        ],
        $position: 0,
      },
    },
  },
  { new: true }
)

if (!restaurant) return res.sendStatus(500)

const subsidiary = restaurant.subsidiaries[0]
res.send(subsidiary)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM