使用拉入猫鼬模型

时间:2015-04-08 01:22:18

标签: node.js mongodb mongoose subdocument

这应该有用吗?我正在尝试从following模型中的文档(this)中删除单个子文档(UserSchema)。

UserSchema.methods.unFollow = function( id ) {
var user = this

return Q.Promise( function ( resolve, reject, notify ) {
    var unFollow = user.following.pull( { 'user': id } )

    console.log( unFollow )

    user.save( function ( error, result ) {
        resolve( result )   
    })  
})
}

这些是模式:

var Follows = new mongoose.Schema({
    user: String,
    added: Number
})

var UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    following: [ Follows ]
})

用户controller.js

/*
Unfollow user.
*/
exports.unFollow = function ( req, res ) {

    User.findOne( { token: req.token }, function ( error, user ) {
        user.unfollow( req.body.id )
        .onResolve( function ( err, result ) {
            if ( err || !result ) return res.status( 500 ).json( "User could not be unfollowed." )

            return res.status( 200 ).json( "User unfollowed." )
        })
    })
}

用户model.js

/*
Unfollow a user.
*/
UserSchema.method( 'unfollow', function unfollow ( id ) {
    this.following.pull( { user: id } )

    return this.save()
})

2 个答案:

答案 0 :(得分:2)

您通常使用method函数分配方法:

UserSchema.method('unFollow', function unFollow(id) {
  var user = this;

  user.following.pull({_id: id});
  // Returns a promise in Mongoose 4.X
  return user.save();
});

另外,如上所述,您不需要使用Q,因为save会返回mongoose promise

更新:Mongoose的数组pull方法将用于匹配原始值,但对于子文档对象,它只会匹配_id

更新#2:我刚刚注意到您的更新问题显示您的控制器首先进行查找,修改返回的文档,然后将文档保存回服务器。为什么不创建一个静态而不是一个方法来做你想要的?这对于DB的单次调用而不是每次操作两次都有额外的好处。

示例:

UserSchema.static('unfollow', function unfollow(token, id, cb) {
  var User = this;

  // Returns a promise in Mongoose 4.X
  // or call cb if provided
  return User.findOneAndUpdate({token: token}, {$pull: {follows: {user: id}}}, {new: true}).exec(cb);
});

User.unfollow(req.token, req.body.id).onResolve(function (err, result) {
  if (err || !result) { return res.status(500).json({msg: 'User could not be unfollowed.'}); }

  return res.status(200).json({msg: 'User unfollowed.'})
});

Bonus follow static:

UserSchema.static('follow', function follow(token, id, cb) {
  var User = this;

  // Returns a promise in Mongoose 4.X
  // or call cb if provided
  return User.findOneAndUpdate({token: token}, {$push: {follows: {user: id}}}, {new: true}).exec(cb);
});

User.follow(req.token, req.body.id).onResolve(function (err, result) {
  if (err || !result) { return res.status(500).json({msg: 'User could not be followed.'}); }

  return res.status(200).json({msg: 'User followed.'})
});

答案 1 :(得分:0)

<块引用>

注意:在 "mongoose": "^5.12.13" 中使用。

至于今天 2021 年 6 月 22 日,您可以使用 $in$pull mongodb 运算符从文档数组中删除项目:

父文档:

{
    "name": "June Grocery",
    "description": "Some description",
    "createdDate": "2021-06-09T20:17:29.029Z",
    "_id": "60c5f64f0041190ad312b419",
    "items": [],
    "budget": 1500,
    "owner": "60a97ea7c4d629866c1d99d1",
}

Items 数组中的文档:

        {
            "category": "Fruits",
            "bought": false,
            "id": "60ada26be8bdbf195887acc1",
            "name": "Kiwi",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Toiletry",
            "bought": false,
            "id": "60b92dd67ae0934c8dfce126",
            "name": "Toilet Paper",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Toiletry",
            "bought": false,
            "id": "60b92fe97ae0934c8dfce127",
            "name": "Toothpaste",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Toiletry",
            "bought": false,
            "id": "60b92ffb7ae0934c8dfce128",
            "name": "Mouthwash",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Toiletry",
            "bought": false,
            "id": "60b931fa7ae0934c8dfce12d",
            "name": "Body Soap",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Fruit",
            "bought": false,
            "id": "60b9300c7ae0934c8dfce129",
            "name": "Banana",
            "price": 0,
            "quantity": 1
        },
        {
            "category": "Vegetable",
            "bought": false,
            "id": "60b930347ae0934c8dfce12a",
            "name": "Sombe",
            "price": 0,
            "quantity": 1
        },

查询:

MyModel.updateMany(
    { _id: yourDocumentId },
    { $pull: { items: { id: { $in: itemIds } } } },
    { multi: true }
  );

注意:ItemIds 是一个 ObjectId 数组。见下文:

[
  '60ada26be8bdbf195887acc1',
  '60b930347ae0934c8dfce12a',
  '60b9300c7ae0934c8dfce129'
]