node.js - 如何将数据推送到nodejs mongodb中的另一个模式

标签 node.js mongodb express mongoose ejs

感谢您点击我的问题..

我在 mongodb 中有两个模式,citySchema 和 destinationSchema。我想建立一对多的关系。每个目的地有一个城市,而该城市又有多个目的地。

这是我的destinationSchema

var mongoose = require("mongoose");
var destinationSchema = new mongoose.Schema({
  name: String,
  image: String,
  description: String,
  city: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "City"
  }
});

module.exports = mongoose.model("Destination", destinationSchema);

这是citySchema

var mongoose = require("mongoose");
var citySchema = new mongoose.Schema({
  name: String,
  image: String,
  description: String,
  destinations: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Destination"
    }
  ]
});

module.exports = mongoose.model("City", citySchema);

这是创建新目的地的后路由

router.post("/", function(req, res) {
  var name = req.body.name;
  var image = req.body.image;
  var description = req.body.description;
  var city = req.body.city;
  var newDestination = {
    name: name,
    image: image,
    description: description,
    city: city
  };
  Destination.create(newDestination, function(err, newCreatedDestination) {
    if (err) {
      console.log(err);
    } else {
      res.redirect("/admin/destinations");
    }
  });
});

这是我的表单,用于创建新目的地

<select name="city">
   <% cities.forEach(function(city) { %>
      <option value=<%=city._id%> > <%= city.name %> </option>
   <% }) %>
 </select>

效果很好。但我希望当我创建新目的地时,它将当前目的地 ID 推送到城市架构(目的地数组)

抱歉我的英语不好。我感谢您的每一个回答和建议。谢谢你😊

最佳答案

创建新目的地后,您可以将该目的地的 ID 推送到城市目的地。

您可以使用以下路线:

router.post("/", async (req, res) => {
  try {
    const { name, image, description, city } = req.body;

    let newDestination = { name, image, description, city };

    newDestination = await Destination.create(newDestination);

    let result = await City.findByIdAndUpdate(
      city,
      {
        $push: { destinations: newDestination._id }
      },
      { new: true }
    );

    res.redirect("/admin/destinations");
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

让我们有一个像这样的现有城市:

{
    "destinations": [],
    "_id": "5e071f212e9ecd31508785c6",
    "name": "Padang",
    "image": "image 1",
    "description": "beautiful city",
    "__v": 0
}

如果我们想将此城市添加为目的地,我们可以将此请求正文发送到我们的发布路由。请注意,作为城市值,我们需要使用现有的城市 ID (5e071f212e9ecd31508785c6),就像我们已有的城市 ID 一样。

{
    "name": "destination name",
    "image": "destination image",
    "description": "destination description",
    "city": "5e071f212e9ecd31508785c6"
}

结果将是这样的:

创建了一个新目的地:

{
    "_id" : ObjectId("5e071fd51cd3600bb083b5e7"),
    "name" : "destination name",
    "image" : "destination image",
    "description" : "destination description",
    "city" : ObjectId("5e071f212e9ecd31508785c6"),
    "__v" : NumberInt(0)
}

并添加到城市:

{
    "_id" : ObjectId("5e071f212e9ecd31508785c6"),
    "destinations" : [
        ObjectId("5e071fd51cd3600bb083b5e7")
    ],
    "name" : "Padang",
    "image" : "image 1",
    "description" : "beautiful city",
    "__v" : NumberInt(0)
}

关于node.js - 如何将数据推送到nodejs mongodb中的另一个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59508463/

相关文章:

node.js - 使用 npm list 时 'invalid' 是什么意思?

mongodb - 如何在聚合管道中执行 $match 阶段时添加限制

mongodb - 是否可以在cosmos mongodb中的多重嵌套字段上创建索引?

node.js - RethinkDB/地平线 : Integration with Express: Access Horizon data server-side?

javascript - 为什么我们不能将数据作为 javascript 对象而不是 JSON 对象发送?

javascript - 等待 AWS SNS 发布回调将值返回给调用方法

javascript - 如何使用给定 ID 进行快速重定向?

mongodb - Mongo 对象 ID : Safe to use in the wild?

node.js - 使用 HBS strip (消耗?)Handlebars 客户端模板进行快速 View 渲染

node.js - Passport-jwt 不同的 token 相同的结果