【问题标题】:MEAN Mongodb replace collection and create documentsMEAN Mongodb 替换集合并创建文档
【发布时间】:2016-10-01 23:20:54
【问题描述】:

所以我有这样的架构:

var article = new mongoose.Schema({
    title : String,
    comments : [{
        pe: mongoose.Schema.Types.ObjectId,
        ref: 'Comment'
    }]
});

和:

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

现在我有了我的小型 Angular 应用程序,当我使用我的 API 和文章检索时,我得到如下信息:

{
    title : "please help me"
    comments : []
}

现在我在前端推送了一些 cmets,新对象是:

{
    title : "please help me"
    comments : [{
        text : "Now, go f**k yourself",
        date : "1 January 1970 00:00:00 UTC."
    }]
}

当我调用 API 并更新文档时,我希望 mongo 自己创建子对象 cmets,有没有办法? 它应该自动执行吗?

【问题讨论】:

    标签: angularjs mongodb express mongoose mean


    【解决方案1】:

    我会这样写一篇文章架构(免责声明:我没有尝试过猫鼬):

    var article = new mongoose.Schema({
        _id: String  // or mongodb.ObjectId? I'm not sure.
        title : String,
        comments : [{
            _id: String    // this field is not nessesary
            text: String,
            date: String
        }]
    });
    
    var comment = new mongoose.Schema({
        created : Date,      // created or date?
        text : String
    });
    

    当你用你的 api 检索时,你会得到类似的东西:

    {
      "_id": "ndrjgnd..fesf",
      "title": "grdgrdgr",
      comments: [ {"text": "hello", "created": "2016:...:"}, ... , ] 
    }
    

    然后就可以从前端推送新的cmets了:

    {
      "articleId": "ndrjgnd..fesf",     // this is important.
      "text": "balabala"
    }
    

    并更新数据库:db.article.update( {_id: ariticleId}, {$push: newComment})

    【讨论】:

    • 没错,是我试图简化示例中的结构。在我的应用程序中,对象注释具有复杂的结构,我更喜欢将它单独放在另一个模式中,因为我应该能够查询它。
    • @GaetanoPessa 那么,有什么问题
    • 我不是专家,我的想法是,如果我尝试在数据库中保存一个带有数组的 json 对象(包含注释的数组),该对象具有结构就像架构中的那个一样,mongo 应该自动识别是评论并创建我的评论对象。这不会发生。正常吗?
    • @GaetanoPessa mongo 对您的架构一无所知。你得到了你放入 mongo 的东西。 IMO,mongo 在关系数据方面做得不好。在文章中存储评论对象或评论引用都不是一个好主意。查询语句比传统数据库更复杂。
    • dow... 那么如何在 mongo 中存储关系数据?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2012-10-07
    • 2022-01-17
    • 2015-07-05
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多