[NodeJS] Mongoose ref关联删除数据

来源:互联网 发布:免费淘客软件 编辑:程序博客网 时间:2024/05/22 17:03

环境

  • Node: v7.0.0
  • Bluebird: v3.4.6
  • Mongoose: v4.6.8

参考文档

ECMAScript 6 入门 —— Promise对象, 阮一峰
Mongoose 之 Population 使用, aikin
Mongoose API v4.7.2

语句

Model.update(conditions, {$pull: {field: value}}, [options], [callback])

若想要同时更新多个匹配的User,则要在 [option] 处添加参数,{multi: true}

Model.update 的具体使用方法详见Mongoose 帮助文档。

样例

Model

存放在了 model.js 中。

var mongoose = require('mongoose');mongoose.Promise = require('bluebird');var Schema = mongoose.Schema;var userSchema = new Schema({  name: String,  age: Number,  posts: [{type: Schema.Types.ObjectId, ref: 'post'}],  comments: [{type: Schema.Types.ObjectId, ref: 'comment'}]});var User = mongoose.model('user', userSchema);var postSchema = new Schema({  title: String,  content: String,  author: {type: Schema.Types.ObjectId, ref: 'user'},  comments: [{type: Schema.Types.ObjectId, ref: 'comment'}]});var Post = mongoose.model('post', postSchema);var commentSchema = new Schema({  content: String,  author: {type: Schema.Types.ObjectId, ref: 'user'}})var Comment = mongoose.model('comment', commentSchema);exports.User = User;exports.Post = Post;exports.Comment = Comment;

上面的 Model 实现了,User->PostUser->CommentPost->UserPost->CommentComment->User的关联。

存储测试数据

var User = require('./model').User;var Post = require('./model').Post;var Comment = require('./model').Comment;var Promise = require('bluebird');var user_tom = new User({name: 'Tom', age: 19});var user_jerry = new User({name: 'Jerry', age: 22});var user_david = new User({name: 'David', age: 15});var post_test = new Post({title: 'test', content: 'wakaka'});var comment_walala = new Comment({content: 'walala'});Promise.all([user_tom.save(), user_jerry.save(), user_david.save()]).spread(function(utom, ujerry, udavid) {  post_test.author = utom;  comment_walala.author = utom;  return Promise.all([post_test.save(), comment_walala.save(), utom, udavid]);}).spread(function(post, comment, utom, udavid) {  utom.posts.push(post);  utom.comments.push(comment);  udavid.comments.push(comment);  post.comments.push(comment);  return Promise.all([utom.save(), post.save(), udavid.save()]);}).spread(function() {  console.log('success');}).catch(function(reason) {  console.log(reason);});

这里创建了 3 个 User,1 个 Post, 1 个 Commentuser_Tomuser_davidcomments 关联到 comment_walalacomment_walalapost_testauthor 关联到 user_Tompost_testcomments 关联到 comment_walala

mongo 连接到 mongodb 查看一下。

> db.users.find().pretty(){    "_id" : ObjectId("584baa387378d64d6e8a9fd6"),    "name" : "Tom",    "age" : 19,    "comments" : [        ObjectId("584baa387378d64d6e8a9fda")    ],    "posts" : [        ObjectId("584baa387378d64d6e8a9fd9")    ],    "__v" : 1}{    "_id" : ObjectId("584baa387378d64d6e8a9fd7"),    "name" : "Jerry",    "age" : 22,    "comments" : [ ],    "posts" : [ ],    "__v" : 0}{    "_id" : ObjectId("584baa387378d64d6e8a9fd8"),    "name" : "David",    "age" : 15,    "comments" : [        ObjectId("584baa387378d64d6e8a9fda")    ],    "posts" : [ ],    "__v" : 1}> db.posts.find().pretty(){    "_id" : ObjectId("584baa387378d64d6e8a9fd9"),    "author" : ObjectId("584baa387378d64d6e8a9fd6"),    "title" : "test",    "content" : "wakaka",    "comments" : [        ObjectId("584baa387378d64d6e8a9fda")    ],    "__v" : 1}> db.comments.find().pretty(){    "_id" : ObjectId("584baa387378d64d6e8a9fda"),    "author" : ObjectId("584baa387378d64d6e8a9fd6"),    "content" : "walala",    "__v" : 0}

图示
这里写图片描述

删除和查询结果

代码

var User = require('./model').User;var Post = require('./model').Post;var Comment = require('./model').Comment;var Promise = require('bluebird');Comment.findOne({content: 'walala'}).then(function(comment) {  return User.update({comments: {$in: [comment._id]}}, {$pull: {'comments': comment._id}}, {multi: true}).exec();}).then(function(res) {  console.log(res);});

因为加了 {multi: true},所以会同时更新所有匹配到的User

返回值

{ ok: 1, nModified: 2, n: 2 }

表示成功,修改了 2 个。

在查询一下数据库。

> db.users.find().pretty(){    "_id" : ObjectId("584baa387378d64d6e8a9fd6"),    "name" : "Tom",    "age" : 19,    "comments" : [ ],    "posts" : [        ObjectId("584baa387378d64d6e8a9fd9")    ],    "__v" : 1}{    "_id" : ObjectId("584baa387378d64d6e8a9fd7"),    "name" : "Jerry",    "age" : 22,    "comments" : [ ],    "posts" : [ ],    "__v" : 0}{    "_id" : ObjectId("584baa387378d64d6e8a9fd8"),    "name" : "David",    "age" : 15,    "comments" : [ ],    "posts" : [ ],    "__v" : 1}

Tom 和 David 的comments内容已经没了。

以上所有,如有错误,麻烦指出,我会及时更改的。

0 0
原创粉丝点击