MEAN Mongodb取代集合并创建文档

时间:2016-06-02 09:43:10

标签: angularjs mongodb express mongoose mean

所以我有这样的架构:

getWindow().setBackgroundDrawable

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

现在我有了我的小角度应用程序,当我使用我的API和文章检索时,我得到类似的东西:

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

现在在前端我推了一些评论,新对象是:

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

当我调用API并更新文档时,我希望mongo能够自己创建子对象注释,有没有办法? 它应该自动完成吗?

1 个答案:

答案 0 :(得分:0)

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

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:...:"}, ... , ] 
}

然后你可以从前端推送新的评论:

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

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