原文地址: http://tech-blog.maddyzone.com/node/add-update-delete-object-array-schema-mongoosemongodb
本文為上面文章的翻譯版本,以學習和鍛煉為宗旨,文中一些術語為了避免歧義保留英文名稱
大多數情況下,我們使用node.js的時候會使用MongoDB, 然后在寫MongoDB相關的驗證、轉換和業務邏輯時我們會經常使用Mongoose。 這里我分享一些關於Array Schema的使用技巧。 當你讀完這篇文章的時候,你將了解如何在Mongoose中增加、更新和刪除一個Array Schema中的對象。
本文將涵蓋:
- 如何在Mongoose中定義Array Schema
- 如何在Mongoose中向Array Schema增加一個值或者對象
- 如何在Mongoose中更新Array Schema中的一個值或者對象
- 如何在Mongoose中刪除Array Schema中的一個值或者對象
Ok, Lest' Start.
1. 如何在Mongoose中定義Array Schema
首先,我們要定義一個基本的名為Article
的Mongoose Schema。 這里我們將Comments
定義為一個Array Schema類型。 不必要關注於所有的代碼,只需要關注在Comments
,這是本文討論的重點。
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
/**
* Article Schema
*/
var ArticleSchema = new Schema({
title: {type:String, required:true},
createdAt: { type: Date, default: Date.now },
description:{type:String, required:true},
tags: [String],
comments: [{ post: String,
posted: {type: Date, default: Date.now}
}]
});
mongoose.model('Article', ArticleSchema);
這里我們假設我們已經在article集合中創建了一些向下面這樣的數據,現在還沒有任何comments:
{
"_id" : ObjectId("54fcb3890cba9c4234f5c925"),
"title" : "A test Article",
"description" : "test article description",
"tags" : [
"test tag"
],
"createdAt" : ISODate("2015-03-08T20:39:37.980Z")
}
2.如何在Mongoose中向Array Schema增加一個值或者對象
當我們添加了一個article后,我們應該可以向comments中添加任意數量的數據。比如當有新的評論時,我們要將該條評論添加到comments屬性中,我們看如何做。
假設請求中我們可以拿到articleid
用來指定需要向哪個article中添加評論,POST的地址像下面這樣:
/api/comments/:articleid
接下來按下面的方式來操作,我們使用了findByIdAndUpdate
假設請求的參數中articleid
是54fcb3890cba9c4234f5c925
var article_id = req.params.articleid;/** assume here we get 54fcb3890cba9c4234f5c925 id
of article as shown in our demo json bve
"_id" : ObjectId("54fcb3890cba9c4234f5c925"),
**/
/** assume your req.body like is below
you can set your logic your own ways
for this article i am assuming that data
would come like below
**/
//req.body={post: "this is the test comments"};
Article.findByIdAndUpdate(
article_id,
{ $push: {"comments": req.body}},
{ safe: true, upsert: true},
function(err, model) {
if(err){
console.log(err);
return res.send(err);
}
return res.json(model);
});
主要是使用下面這行代碼我們就可以將數據插入到Array Schema:
{ $push: {"comments": req.body}}
上面的操作執行之后,在MongoDB中的數據如下:
{
"_id" : ObjectId("54fcb3890cba9c4234f5c925"),
"title" : "A test Article",
"description" : "test article description",
"tags" : [
"test tag"
],
"createdAt" : ISODate("2015-03-08T20:39:37.980Z"),
"comments" : [
{
"post" : "this is the test comments",
"_id" : ObjectId("54fe0976250888001d5e6bc4"),
"posted" : ISODate("2015-03-09T20:58:30.302Z")
}
]
}
3.如何在Mongoose中更新Array Schema中的一個值或者對象
對於更新操作,我們假設請求中帶有articleid
和commentid
,來定位我們想更新哪個article中的哪個comment.
PUT地址像下面這樣:
/api/comments/:articleid/:commentid
更新代碼:
Article.update({'comments._id': comment_id},
{'$set': {
'comments.$.post': "this is Update comment",
}},
function(err,model) {
if(err){
console.log(err);
return res.send(err);
}
return res.json(model);
});
現在再看下MongoDB中的數據:
{
"_id" : ObjectId("54fcb3890cba9c4234f5c925"),
"title" : "A test Article",
"description" : "test article description",
"tags" : [
"test tag"
],
"createdAt" : ISODate("2015-03-08T20:39:37.980Z"),
"comments" : [
{
"post" : "this is Update comment",
"_id" : ObjectId("54fe0976250888001d5e6bc4"),
"posted" : ISODate("2015-03-09T20:58:30.302Z")
}
]
}
所以使用下面這樣的代碼可以更新Array Schema的數據:
{'$set': {
'comments.$.post': "this is Update comment",
}},
4.如何在Mongoose中刪除Array Schema中的一個值或者對象
和更新一樣,假設請求中有articleid
和commentid
,來定位我們想刪除哪個article中的哪個comment.
DELETE地址如下:
/api/comments/:articleid/:commentid
跟上面的操作一樣,我們使用findByIdAndUpate
方法:
var article_id = req.params.articleid,//assume get 54fcb3890cba9c4234f5c925
comment_id = req.params.commentid;// assume get 54fcb3890cba9c4234f5c925
Article.findByIdAndUpdate(
article_id,
{ $pull: { 'comments': { _id: comment_id } } },function(err,model){
if(err){
console.log(err);
return res.send(err);
}
return res.json(model);
});
執行之后,查看數據庫中的數據:
{
"_id" : ObjectId("54fcb3890cba9c4234f5c925"),
"title" : "A test Article",
"description" : "test article description",
"tags" : [
"test tag"
],
"createdAt" : ISODate("2015-03-08T20:39:37.980Z"),
"comments" : []//remove comments
}
使用下面的代碼可以刪除Array Schema中的數據:
{ $pull: { 'comments': { _id: comment_id } } }