这个问题很基本: 我想在mongodb中用mongoose保存嵌套对象,但是当我保存它们时,嵌套对象为空
我已经尝试过对此问题的其他解决方案,但这并不能解决我的问题。 推送对象、填充等......但这仅在您需要该信息而不保存它时才有效。 所以我来了。
型号
const mongoose = require('mongoose')
let Schema = mongoose.Schema
const respuestaSchema = new Schema({
resp:{type:String},
value:{type:String}
},{ _id : false })
const preguntasSchema = new Schema({
pregunta:{type:String},
tipo:{type:String},
respuesta:[respuestaSchema]
},{ _id : false })
let testSchema = Schema({
_id:{type:Schema.ObjectId, auto:true},
name: {type:String},
dName:{type:String},
categoria:{type:[Schema.ObjectId],ref:'categoria'},
preguntas:[preguntasSchema]
},{versionKey:false})
module.exports = mongoose.model('test',testSchema)
保存测试:
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 上看到我传递的所有信息,但我只看到不是嵌套对象的信息,以及嵌套对象的标题但为空。 如果您需要在数据库中捕获问题的图像,我可以发送。 希望您能帮助我了解这些信息。
最佳答案
我根据您声明的方案编辑了您的代码,请尝试:
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
};
关于javascript - 使用 mongoose 保存嵌套对象(数组),在 mongodb 中结果为空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783607/