[原译]在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中的对象。
本文将涵盖:
- 如何在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 } } }
总结

[原译]在mongoose中对Array Schema进行增删改的更多相关文章
- JS中对数组元素进行增删改移
在js中对数组元素进行增删改移,简单总结了一下方法: 方法 说明 实例 push( ); 在原来数组中的元素最后面添加元素 arr.push("再见58"); unshift( ) ...
- kibana的Dev Tool中如何对es进行增删改查
kinaba Dev Tool中对es(elasticSearch)进行增删改查 一.查询操作 查询语句基本语法 以下语句类似于mysql的: select * from xxx.yyy.topic ...
- 在ASP.NET MVC中对表进行通用的增删改
http://www.cnblogs.com/nuaalfm/archive/2009/11/11/1600811.html 预备知识: 1.了解反射技术 2.了解C#3.0中扩展方法,分布类,Lin ...
- Django中对单表的增删改查
之前的简单预习,重点在后面 方式一: # create方法的返回值book_obj就是插入book表中的python葵花宝典这本书籍纪录对象 book_obj=Book.objects.creat ...
- Django学习笔记--数据库中的单表操作----增删改查
1.Django数据库中的增删改查 1.添加表和字段 # 创建的表的名字为app的名称拼接类名 class User(models.Model): # id字段 自增 是主键 id = models. ...
- Django中ORM对数据库的增删改查操作
前言 什么是ORM? ORM(对象关系映射)指用面向对象的方法处理数据库中的创建表以及数据的增删改查等操作. 简而言之,就是将数据库的一张表当作一个类,数据库中的每一条记录当作一个对象.在 ...
- (数据科学学习手札126)Python中JSON结构数据的高效增删改操作
本文示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 在上一期文章中我们一起学习了在Python ...
- Django中ORM对数据库的增删改查
Django中ORM对数据库数据的增删改查 模板语言 {% for line in press %} {% line.name %} {% endfor %} {% if 条件 %}{% else % ...
- mongoose 的 model,query:增删改查
简介 mongoose是node.js的一个操作mongodb的模块,比起之前mongodb模块,只需要在开始时连接,不需要手动关闭,十分方便. 连接mongodb 首先你需要安装mongodb.有了 ...
随机推荐
- unity3d 血液
这里的人物头像和血条是在3d世界生成的,所以有真正的纵深感和遮挡关系,废话不多说,看我是怎么实现的. 第一步.先在UI Root里制作头像和血条. 这个制作步骤基本和我前面一篇文章介绍头像血条的制作步 ...
- Erlang运行时的错误
Erlang运行时发生错误时,会返回一些错误信息,理解这些信息,对于学好.用好Erlang来说是必要. Erlang中的运行错误包括:badarg, badarith, badmatch, funct ...
- avalonjs 1.3.7发布
avalonjs 1.3.7发布 又到每个月的15号了,现在avalon已经固定在每个月的15号发布新版本.这次发布又带来许多新特性,让大家写码更加轻松,借助于“操作数据即操作DOM”的核心理念与双向 ...
- leetcode[60] Rotate List
题目:给定链表,和一个k,把链表的后k个旋转到前头,例如链表为: 1->2->3->4->5->NULL and k = 2, return 4->5->1- ...
- three.js 源代码凝视(十六)Math/Frustum.js
商域无疆 (http://blog.csdn.net/omni360/) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:商域无疆 - 本博客专注于 敏捷开发 ...
- 【Web.xml配置具体解释之context-param
】
转自:http://blog.csdn.net/liaoxiaohua1981/article/details/6759206 格式定义: [html] view plaincopy <cont ...
- Building Modern Web Apps-构建现代的 Web 应用程序
Building Modern Web Apps-构建现代的 Web 应用程序 视频长度:1 小时左右 视频作者:Scott Hunter 和 Scott Hanselman 视频背景:Visual ...
- MySQL5.7 安装过程中出现 attempting to start service 过不去
MySQL5.7 安装过程中出现 attempting to start service 过不去. 1,机制打开服务,把MySql服务名启动(我的是MySqlAliyun) 启动失败:提示1067错误 ...
- NET Framework 4.5新特性 数据库的连接加密保护。
NET Framework 4.5新特性 (一) 数据库的连接加密保护. NET Framework 4.5 ado.net数据库连接支持使用SecureString内存流方式保密文本. 一旦使用这 ...
- css 初始化
html,body,h1,h2,h3,h4,h5,h6,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,figure,table,caption,th,td,for ...