从用户输入中检索数据并将其保存到猫鼬模型中
这是我的模型模式:
const DemoSchema = new Schema({
rowOne: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
rowTwo: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
});
当我这样做时,它将数据保存到我的模型中:
const product = await new Regal({
rowOne: { colOne: { two: { name: productName, qty: productQty } } },
});
product.save();
我的问题是,如何用用户输入替换 rowOne、colOne 和 2?
我尝试过:
const row = req.body.rows // this must be rowOne or rowTwo
const column = req.body.column // colOne or other (colOne to colNine)
const col = req.body.col // one, two or three
const productName = req.body.name
const productQty = req.body.qty
尝试 1:
const product = await new Regal({ `${row}`: { `${column}`: { `${col}`: { name: productName, qty: productQty }}}});
'错误 -->预计财产分配。
尝试 2:
const product = await new Regal(`{${row}: { ${column}: { ${col}: { name: ${productName}, qty: ${productQty} } } } }`);
'错误 --> Document() 的参数“obj”必须是一个对象,得到 {rowOne: { colOne: { one: { name: Milk, količina: 250 } } } }'
This is my model shema:
const DemoSchema = new Schema({
rowOne: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
rowTwo: {
colOne: {
one: {
name: String,
qty: Number,
},
two: {
name: String,
qty: Number,
},
three: {
name: String,
qty: Number,
},
},
},
});
When I do this it saves data to my model:
const product = await new Regal({
rowOne: { colOne: { two: { name: productName, qty: productQty } } },
});
product.save();
My question is, how can I replace rowOne, colOne and two with user input?
I tried this:
const row = req.body.rows // this must be rowOne or rowTwo
const column = req.body.column // colOne or other (colOne to colNine)
const col = req.body.col // one, two or three
const productName = req.body.name
const productQty = req.body.qty
Attempt 1:
const product = await new Regal({ `${row}`: { `${column}`: { `${col}`: { name: productName, qty: productQty }}}});
'Error --> Property Assignment expected.'
Atempt 2:
const product = await new Regal(`{${row}: { ${column}: { ${col}: { name: ${productName}, qty: ${productQty} } } } }`);
'Error --> Parameter "obj" to Document() must be an object, got {rowOne: { colOne: { one: { name: Milk, količina: 250 } } } }'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用方括号将变量用作对象的键。
这将创建一个类似
{username:saloni}
的对象。通过这种方式,您可以将 rowOne、colOne 和 Two 替换为用户输入,将它们存储在变量中,然后使用它们。
You can use variables as keys of objects using square brackets.
this will create an object like
{username:saloni}
.This way you can replace rowOne, colOne, and two with user input by storing them in a variable and then use it.