Mongodb | mongoose:使用$ pull

时间:2016-05-30 22:39:19

标签: node.js mongodb mongoose

我有以下两种模式:

捕获

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = Schema({
    type: String,
    birdname: {type: String, required: true},
    place: String,
    note: String,
    userId: String,
    author: String,
    picture: Schema.Types.Mixed,
    created_at: Date,
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}],
});

module.exports = mongoose.model('Capture', captureSchema);

注释

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = Schema({
    body: String,
    userId: String,
    author: String,
    created_at: Date,
    capture: [{ type: Schema.Types.ObjectId, ref: 'Capture'}]
});

module.exports = mongoose.model('Comment', commentSchema);

我的目标是从捕获中删除评论,但我似乎无法弄清楚如何删除参考号码'一旦我删除了评论,就从捕获中获取。

目前我正在使用以下内容删除评论:

var Comment = require('../models/comment');
var Capture = require('../models/capture');

...

router.delete('/comments/:id', function(req, res){
         Comment.remove({_id: req.params.id}, function(err){
             res.json({result: err ? 'error' : 'ok'});
             console.log('comment removed');
         });

           //DOES NOT WORK ---> Need assistance with $pull
            Capture.update({_id: Capture.comments._id}, {
             $pull : {'comments' : req.params.id}}, function(err, data) {
                if(err) throw err;
                res.json(
         });
     });

但出于某种原因,只有我的评论被删除了,但是参考文献仍然保留在我的捕获中(例如):

{
    "_id": "574b640e39c34ad806b7eab6",
    "created_at": "2016-05-29T21:50:06.772Z",
    "picture": "https://cdn.filepicker.io/api/file/C9Z73CQwCiFP8pdB5W7A",
    "author": "Cedric Bongaerts",
    "userId": "facebook|10153403872376529",
    "place": "Afrika",
    "birdname": "Mountain Serpent Eagle",
    "type": "ok",
    "__v": 14,
    "comments": [
                "574cbfa6ab7e2b44184584df",
                "574cbfa6ab7e2b4682452fss",
                "574cb61vdz422b57584d417s",
                ]
}

虽然我的评论是空的(已被删除)。

修改 还有一点需要提及: 当我通过' id' /api/captures/:capture,它确实显示评论已删除..仅在查看完整捕获列表/api/captures

时才会停留

1 个答案:

答案 0 :(得分:2)

您需要获取要删除的评论文档,以便可以访问包含capture文档的_id的{​​{1}}字段,以从中删除评论参考。最简单的方法是在删除评论时使用findByIdAndRemove而不是Capture

remove

请注意,这假设Comment.findByIdAndRemove(req.params.id, function(err, comment){ if (comment) { Capture.update({_id: comment.capture}, { $pull : {comments: req.params.id} }, function(err, data) { ... }); } }); 不是数组(如注释中所述),而是定义如下:

capture