[原译]在mongoose中对Array Schema进行增删改

原文地址: http://tech-blog.maddyzone.com/node/add-update-delete-object-array-schema-mongoosemongodb

本文为上面文章的翻译版本,以学习和锻炼为宗旨,文中一些术语为了避免歧义保留英文名称

大多数情况下,我们使用node.js的时候会使用MongoDB, 然后在写MongoDB相关的验证、转换和业务逻辑时我们会经常使用Mongoose。 这里我分享一些关于Array Schema的使用技巧。 当你读完这篇文章的时候,你将了解如何在Mongoose中增加、更新和删除一个Array Schema中的对象。

本文将涵盖:

  1. 如何在Mongoose中定义Array Schema
  2. 如何在Mongoose中向Array Schema增加一个值或者对象
  3. 如何在Mongoose中更新Array Schema中的一个值或者对象
  4. 如何在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
假设请求的参数中articleid54fcb3890cba9c4234f5c925

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中的一个值或者对象

对于更新操作,我们假设请求中带有articleidcommentid,来定位我们想更新哪个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中的一个值或者对象

和更新一样,假设请求中有articleidcommentid,来定位我们想删除哪个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 } } }

总结

posted @ 2015-12-03 17:56  le0zh  阅读(2742)  评论(0编辑  收藏  举报