Sto costruendo un'API in node.js che utilizza mongodb e mangusta. Attualmente ho un documento incorporato all'interno di un documento incorporato (Schema all'interno di uno schema) che non è semplicemente persistente nel database, e ho provato tutto quello che posso ma senza fortuna.Come aggiornare un documento incorporato in un documento incorporato in mangusta?
Ho dello schema definito nella mangusta come:
var BlogPostSchema = new Schema({
creationTime: { type: Date, default: Date.now },
author: { type: ObjectId, ref: "User" },
title: { type: String },
body: { type: String },
comments: [CommentSchema]
});
var CommentSchema = new Schema({
creationTime: { type: Date, default: Date.now },
user: { type: ObjectId, ref: "User" },
body: { type: String, default: "" },
subComments: [SubCommentSchema]
});
var SubCommentSchema = new Schema({
creationTime: { type: Date, default: Date.now },
user: { type: ObjectId, ref: "User" },
body: { type: String, default: "" }
});
E il codice eseguo è la seguente:
// Create a comment
app.post("/posts/:id/comments", function(req, res, next) {
Posts.find({ _id : req.params.id }, function(err, item){
if(err) return next("Error finding blog post.");
item[0].comments.push(new Comment(JSON.parse(req.body)));
item[0].save(); // <= This actually saves and works fine
respond(req, res, item[0].comments, next);
});
});
// Create a subcomment
app.post("/posts/:id/comments/:commentid/subcomments", function(req, res, next) {
Posts.find({ _id : req.params.id }, function(err, item){
if(err) return next("Error finding blog post.");
item[0].comments[req.params.commentid - 1].subcomments.push(new SubComment(JSON.parse(req.body)));
item[0].save(); // <= This completes (without error btw) but does not persist to the database
respond(req, res, item[0].comments[req.params.commentid - 1].subcomments, next);
});
});
posso creare i post con commenti senza problema, ma per qualche ragione Non riesco a creare sottocommenti su un commento. Il documento Blog Post ha effettivamente i commenti e le sottomissioni allegati quando si stampa sulla console durante l'esecuzione - solo che non salva nel database (salva il post del blog con un commento, ma senza sottomissioni).
ho cercato di "markModified" sulla matrice commenti, ma nessun cambiamento:
Posts.markModified("comments"); // <= no error, but also no change
...
Posts.comments.markModified("subcomments"); // <= produces an error: "TypeError: Object [object Object] has no method 'markModified'"
Ora sto pensando che potrebbe essere necessario lanciare l'oggetto da MongoDB in qualche modo? Come forse non riconosce il commento e il sottocomposto come documenti di mangusta? – Rory