Javascript 使用mongoose保存嵌套对象(数组),在mongodb中生成空对象
问题是如此基本: 我想用mongodb中的mongoose保存嵌套对象,但保存它们时,嵌套对象为空 我已经尝试过其他方法来解决这个问题,但这并不能解决我的问题。 推动对象、填充等。。但这只在你需要信息而不是保存信息时才起作用。 我来了 模型 保存测试:Javascript 使用mongoose保存嵌套对象(数组),在mongodb中生成空对象,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,问题是如此基本: 我想用mongodb中的mongoose保存嵌套对象,但保存它们时,嵌套对象为空 我已经尝试过其他方法来解决这个问题,但这并不能解决我的问题。 推动对象、填充等。。但这只在你需要信息而不是保存信息时才起作用。 我来了 模型 保存测试: const Test = require('../models/test') exports.newTest = function(req,res){ let param = req.body let nTest = new T
const Test = require('../models/test')
exports.newTest = function(req,res){
let param = req.body
let nTest = new Test()
nTest.name = param.name
nTest.dName = param.dName
nTest.categoria = param.categoria
nTest.pregunta = param.pregunta
nTest.tipo = param.tipo
nTest.resp = param.resp
nTest.value = param.value
nTest.preguntas.push(nTest)
nTest.save().then(
testSaved=>{
res.status(200).send({accion:'newTest',mensaje:'Test creado correctamente'})
}
).catch(err=>{res.status(500).send({accion:'newTest',mensaje:'Error en creacion de test ' +err})})
}
我使用nTest.preguntas.push(nTest)
来保存preguntas,它保存了它,但该对象中的信息不会显示,只会显示object[],因为preguntas中有另一个对象
我希望在Compass或Robo3T上看到我传递的所有信息,但我只看到不是嵌套对象的信息,以及嵌套对象的标题,但该标题为空。
如果您需要在db中捕获问题的img,我可以发送。
希望您能帮助我了解这些信息。我编辑了您声明的方案对应的代码,请尝试:
exports.newTest = ({ body: param }, res) => {
const nTest = new Test();
nTest.name = param.name;
nTest.dName = param.dName;
nTest.categoria = param.categoria;
nTest.preguntas = [
{
pregunta: param.pregunta,
tipo: param.tipo,
respuesta: [
{
resp: param.resp,
value: param.value,
},
],
},
];
// your saving func
};
很有效,非常感谢。我无法对答案进行投票,因为我是stackOverflow的新手,但这个答案对我来说很有用。“若要将答案标记为已接受,请单击答案旁边的复选标记,将其从灰色切换为已填写。”@romedu check IIarion Halushka answer,这对我来说很有用。
exports.newTest = ({ body: param }, res) => {
const nTest = new Test();
nTest.name = param.name;
nTest.dName = param.dName;
nTest.categoria = param.categoria;
nTest.preguntas = [
{
pregunta: param.pregunta,
tipo: param.tipo,
respuesta: [
{
resp: param.resp,
value: param.value,
},
],
},
];
// your saving func
};