Buduję API w węźle node.js, który używa mongody i mangusty. Obecnie mam osadzony dokument wewnątrz osadzonego dokumentu (Schemat w schemacie), który po prostu nie jest przechowywany w bazie danych, i próbowałem wszystkiego, co mogłem, ale bez powodzenia.Jak zaktualizować osadzony dokument w osadzonym dokumencie w mangecie?
mam schematu zdefiniowana w mangusta jak:
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: "" }
});
I kod mogę wykonać to w następujący sposób:
// 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);
});
});
mogę stworzyć bloga postów z komentarzami bez problemu, ale z jakiegoś powodu Nie mogę tworzyć subkomisji w komentarzu. Dokument Blog Post zawiera komentarze i podkomisje podczas drukowania na konsolę podczas wykonywania - tylko nie zapisuje w bazie danych (zapisuje post w blogu z komentarzem, ale bez podkomisji).
Próbowałem „markModified” na tablicy komentarze, ale bez zmian:
Posts.markModified("comments"); // <= no error, but also no change
...
Posts.comments.markModified("subcomments"); // <= produces an error: "TypeError: Object [object Object] has no method 'markModified'"
Zastanawiam się, czy nie muszę jakoś wyrzucić obiekt z MongoDB? Być może nie rozpoznajemy komentarza i podkomisji jako dokumentów mangusty? – Rory