Zehef Zehef - 1 month ago 7
Node.js Question

Mongoose create a subobject in a subobject

I want to create a subdocument in a subobject field, not to update.

My Schema:

var DemandeSchema = new Schema({
titre: {
type: String,
required: true
},
description: {
type: String,
required: true
},
type: {
type: String,
required: true
},
answer: {}
});


My code:

demande.update(
{ name: 'answer' },
{ $push: req.body.answer },
{ upsert: true },
function(error, user) {
if (error) return next(error);
else {
return true;
}
}
)

req.body.answer = {
"id": "57f512f4360d8818a4e5ea3d",
"answer": {
"122547eee99" : {
"review" : "1.3",
"login" : "new"
}
}
}


But this code doesn't create a new field in my DB, it just updates the field
answer
when I just want to create a new object field in the answer field.

Actual Result:

{
"_id" : ObjectId("57f512f4360d8818a4e5ea3d"),
"titre" : "TEST",
"description" : "ee",
"type" : "ee",
"__v" : 0,
"answer" : {
"122547eee98" : {
"review" : "8.8",
"login" : "x"
}
}
}


Expected Result:

{
"_id" : ObjectId("57f512f4360d8818a4e5ea3d"),
"titre" : "TEST",
"description" : "ee",
"type" : "ee",
"__v" : 0,
"answer" : {
"122547eee98" : {
"review" : "8.8",
"login" : "x"
},
"122547eee99" : {
"review" : "1.3",
"login" : "new"
}
}
}

Answer
var DemandeSchema = new Schema({
titre: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
type: {
    type: String,
    required: true
},
answer: []
});

Answer field curly braces would convert to square brackets for pushing all new answers. Conclusion: It creates an array.