簡體   English   中英

貓鼬架構參考與嵌入數組

[英]mongoose schema reference vs embed array

我有一個快遞和貓鼬的應用程序。 我有兩個架構,一個Blog架構和一個Comment架構。 我想使用RESTful路由將評論數組從表單推送到單個博客。 如果我在Blog模式中嵌入Comment模式,則它起作用,另一方面,如果我在Blog模式中引用Comment模式的ObjectId,則該代碼適用於第一個注釋,然后在第二個注釋中,控制台將拋出驗證錯誤:

(node:5472) UnhandledPromiseRejectionWarning: 
Unhandled promise rejection (rejection id: 1): 
ValidationError: Blog validation failed: 
comments: Cast to [undefined] failed for value 
"[{
  "_id":"5a57374da3ba43156005c881",
  "text":"test1",
  "author":"test1",
  "__v":0
}]" 
at path "comments"

記錄的對象是我推送到數組的第一個注釋

這是Blog模式(嵌入式版本)

//Embed

var mongoose = require("mongoose");

var comment = new mongoose.Schema({
    text: String,
    author: String
});

var blogSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String,
    comments: [comment]
});

module.exports = mongoose.model("Blog", blogSchema);

這是Blog模式(參考版本)

// Reference

var mongoose = require("mongoose");

var blogSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String,
    comments: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
    }]
});

module.exports = mongoose.model("Blog", blogSchema);

這是Comment Schema

var mongoose = require("mongoose");

var commentSchema = new mongoose.Schema({
    text: String,
    author: String
});

module.exports = mongoose.model("Comment", commentSchema);

這是我用來發布新評論的評論路線

app.post("/blogs/:id/comments", function (req, res) {
    // find the correct campground
    Blog.findById(req.params.id, function (err, blog) {
        if (err) {
            console.log(err);
            res.redirect("/blogs");
        } else {
            Comment.create(req.body.comment, function (err, comment) {
                if (err) {
                    console.log(err);
                } else {
                    blog.comments.push(comment);
                    blog.save();
                    res.redirect("/blogs/" + blog._id);
                }
            });
        }
    });
});

請注意,如果我使用console.log博客或che評論對象,則路由可以正常工作並重定向到“ blogs /:id”頁面,我的輸出正確

最后,這是我用來發布請求的表格:

<div class="container">
    <div class="row">
        <h1 style="text-align: center;">Add a new Comment to <%= blog.name %></h1>
        <div style="width: 30%; margin:25px auto;">
            <form action="/blog/<%= blog._id %>/comments" method="POST">
                <div class="form-group">
                    <input class="form-control" type="text" name="comment[text]" placeholder="text">
                </div>
                <div class="form-group">
                    <input class="form-control"  type="text" name="comment[author]" placeholder="author">
                </div>
                <div class="form-group">
                    <button class="btn btn-lg btn-primary btn-block">Submit!</button>
                </div>
            </form>
            <a href="/blogs">Go Back</a>
        </div>
    </div>
</div>

編輯我寧願只使用注釋的ID而不是完整的注釋架構,但是我不知道如何設置應用程序來做到這一點。

貓鼬github個人資料也報告了相同的錯誤: https : //github.com/Automattic/mongoose/issues/5972

對於參考版本:創建評論后,您只需在博客文檔中推送創建的評論文檔的ID。

blog.comments.push(comment._id); 

要么

blog.comments.push(mongoose.Types.ObjectId(comment._id)); //to ensure the pushed id will be mongoose object id.

您必須在步驟2中要求貓鼬。

我發現解決此問題的唯一方法是重構代碼,使其看起來像這樣:

app.post("/blogs/:id/comments", function (req, res) {
    Comment.create(req.body.comment, function (err, comment) {
        if (err) {
            console.log(err);
        } else {
            Blog.findOne({"_id": req.params.id})
            .populate("comments")
            .exec(function (err, blog) {
                if (err) {
                    console.log(err);
                    res.redirect("/blogs");
                } else {
                    blog.comments.push(comment);
                    blog.save();
                    res.redirect("/blogs/" + blog._id);
                }
            });
        }
    });
});

但是,這不能解釋模式的行為

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM