![](/img/trans.png)
[英]Mongoose - How to push object in nested array of objects
[英]Node/JS mongoose REST API How to push a new object into a nested array of objects all in one collection
Noob MERN Stack Dev 在這里,我正在構建一個小型食品配送實踐網絡應用程序。 我已經開始創建一個基本的 RESTful API 來為我的送餐網站提供服務。
我目前正在嘗試構建數據庫。 我有一個餐廳集合,其中包含每個餐廳都有圖像源、標題、描述和菜單。 菜單是一個嵌套數組。 我想這樣做,以便用戶能夠將新菜單項推送到他們餐廳的菜單數組中,並從該數組中刪除選定的項目。 我一直在試圖弄清楚如何使用補丁來做到這一點,但似乎找不到有效的解決方案。 任何幫助將非常感激。
服務器.JS:
require("dotenv").config()
const express = require("express");
const mongoose = require("mongoose");
const app = express();
mongoose.connect(process.env.DATABASE_URL)
const db = mongoose.connection
db.on("error", () => console.error(error))
db.once("open", () => console.log("connected to database"))
app.use(express.json())
const subscribersRouter = require("./routes/subscribers")
const restaurantsRouter = require("./routes/restaurants")
app.use("/subscribers", subscribersRouter)
app.use("/restaurants", restaurantsRouter)
app.listen(3000, () => {
console.log("Server has started on port 3000")
});
架構和模型:
const mongoose = require("mongoose")
const menueSchema = new mongoose.Schema({
name: String,
price: String,
description: String
})
const restaurantSchema = new mongoose.Schema({
src: {
type: String,
required: true
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
menue: {
type: menueSchema,
required: true
}
})
module.exports = mongoose.model("restaurant", restaurantSchema)
路線:
const express = require("express")
const router = express.Router()
const Restaurant = require("../models/restaurant")
// Getting All
router.get("/", async (req, res) => {
try {
const restaurants = await Restaurant.find()
res.json(restaurants)
} catch (err) {
res.status(500).json({
message: err.message
})
}
})
// Getting One
router.get("/:id", getRestaurant, (req, res) => {
res.json(res.restaurant)
})
// Creating One
router.post("/", async (req, res) => {
const restaurant = new Restaurant({
src: req.body.src,
title: req.body.title,
description: req.body.description,
menue: req.body.menue
})
try {
const newRestaurant = await restaurant.save()
res.status(201).json(newRestaurant)
} catch (err) {
res.status(400).json({
message: err.message
})
}
})
// Updateing One
router.patch("/:id", getRestaurant, async (req, res) => {
if (req.body.name != null) {
res.restaurant.name = req.body.name
}
if (req.body.title != null) {
res.restaurant.title = req.body.title
}
if (req.body.description != null) {
res.restaurant.description = req.body.description
}
if (req.body.menue != null) {
res.restaurant.menue = req.body.menue
}
try {
const updatedRestaurant = await res.restaurant.save()
res.json(updatedRestaurant)
} catch (err) {
res.status(400).json({
message: err.message
})
}
})
// Update Menue
router.patch("/:id", getRestaurant, async (req, res) => {
try {
console.log(res.resturants.menue)
} catch (err) {
}
})
// Deleting One
router.delete("/:id", getRestaurant, async (req, res) => {
try {
await res.restaurant.remove()
res.json({
message: "Deleted Restaurant"
})
} catch (err) {
res.status(500).json({
message: err.message
})
}
})
async function getRestaurant(req, res, next) {
let restaurant
try {
restaurant = await Restaurant.findById(req.params.id)
if (restaurant == null) {
return res.status(404).json({
message: "cannot find Restaurant"
})
}
} catch (err) {
return res.status(500).jsong({
message: err.message
})
}
res.restaurant = restaurant
next()
}
module.exports = router
要求:
# RESTURANTS
# Get All
GET http://localhost:3000/restaurants
###
# Get One
GET http://localhost:3000/restaurants/627e3012afe6e905cd550c9f
###
# Create One
POST http://localhost:3000/restaurants
Content-Type: application/json
{
"src": "https://ychef.files.bbci.co.uk/976x549/p04tx3m6.jpg",
"title": "Joes Burgers",
"description": "Good Fuggen Burgers",
"menue": {
"name": "Burger",
"price": "R50",
"description": "A good Fuggen burger"
}
}
###
#Delete One on ID
DELETE http://localhost:3000/restaurants/627e68802760c784cc5702c1
###
#Update One
PATCH http://localhost:3000/restaurants/627e68f62760c784cc5702c5
Content-Type: application/json
{
"menue": {
"name": "Waffel",
"price": "R20",
"description": "A good Fuggen Waffel"
}
}
我對您的問題的理解是,您分別為餐廳和菜單使用了兩個單獨的集合。 如果您想在菜單集合中推送數據,您必須編寫一個單獨的查詢並在菜單集合中添加餐廳的 id,以便讓您知道哪個餐廳有這個菜單。
另一個選項是您可以在餐廳集合中添加一組對象並將其命名為菜單,然后將數據推送到其中。
const restaurantSchema = new mongoose.Schema({
src: {
type: String,
required: true
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
menue: {
type: Array,
required: true
}})
那將是一個更簡單的選擇...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.