Bootstrap

[NodeJS] Mongoose ref关联删除数据

环境

  • 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;
exp
;