如何创建一个API将表单输入数据推送到mongodb文档作为子文档?



这可以与fetch API哪个方法我应该使用post或put?请回复. .有人能给我完整的api来推动orderSchema作为userSchema的子文档吗?我已经滚动了大量的链接,但我还是找不到任何答案。

这是我在mongodb中使用的模式。


import mongoose from 'mongoose'
const orderSchema = new mongoose.Schema({
rsph: { type: Number },
rcyl: { type: Number },
raxis: { type: Number },
lsph: { type: Number },
lcyl: { type: Number },
laxis: { type: Number },
add: { type: Number },
frame: { type: String },
lens: { type: String }
}, {
timestamps: true
});

const userSchema = new mongoose.Schema({
name: { type: String, required: true },
phone: { type: Number, required: true },
address: { type: String, required: true },
orders: [orderSchema]
}, {
timestamps: true
});

export default mongoose.models.User || mongoose.model('User', userSchema)

我正在使用这个api来保存userschema,这是工作的。


import initDB from '../../helper/initDB';
import User from '../../models/addUser';

initDB()

export default async (req, res) =>{
(req.method)
{
"POST"
await handler(req, res)
}
}
const handler = async (req, res) =>{
if (req.method == 'POST') {
console.log(req.body)
const { name,phone,address } = req.body
let u = new User( {name,phone,address } )
await u.save()
res.status(200).json({ success: "success" })
}
else {
res.status(400).json({ error: "this method is not required" })
}
}


我使用这个api来保存这个数据作为子文档,但这个api不工作,我应该做什么改变?


import initDB from '../../../helper/initDB';
import User from '../../../models/addUser';

initDB()

export default async (req, res) =>{
(req.method)
{
"POST"
await handler(req, res)
}
}
const handler = async (req, res) =>{
if (req.method == 'POST') {
console.log(req.body)
const { uid } = req.query
const user = await User.findOne({ _id: uid })
const { rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens } = req.body
const order = ({ rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens });
user.orders.push(order);
await user.save()
res.status(200).json({ success: "success" })
}
else {
res.status(400).json({ error: "this method is not required" })
}
}

请回复…

从下面一行删除bracket ()

const order = ({ rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens });

只传递对象,如

const order = { rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens };

结尾应该是:

const handler = async (req, res) => {
if (req.method == 'POST') {
console.log(req.body)
const { uid } = req.query
const user = await User.findOne({ _id: uid })
const { rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens } = req.body
const order = { rsph, rcyl, raxis, lsph, lcyl, laxis, add, frame, lens };
user.orders.push(order);
await user.save()
res.status(200).json({ success: "success" })
}
else {
res.status(400).json({ error: "this method is not required" })
}
}

最新更新