使用 Mongoose populate() 清理死引用 [英] Clean up dead references with Mongoose populate()

查看:36
本文介绍了使用 Mongoose populate() 清理死引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户有一个名为tags"的数组:

If a user has an array called "tags":

var User = new Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    tags: [{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Tag',
        required: true
    }],
    created: {
        type: Date,
        default: Date.now
    }
});

我对查询执行了 populate('tags') :

and I do a populate('tags') on a query:

User.findById(req.params.id)
    .populate("tags")
    .exec(function(err, user) { ... });

如果列表中的一个标签实际上已被删除,有没有办法删除标签"中的这个死引用?

If one of the tags in the list has actually been deleted, is there a way to remove this dead reference in "tags"?

当前,返回的用户对象 IS 返回所需的结果——即.只有实际存在的标签才出现在标签数组中……但是,如果我查看 mongodb 中的底层文档,它仍然包含数组中的死标签 ID.

Currently, the returned user object IS returning the desired result -- ie. only tags that actually exist are in the tags array... however, if I look at the underlying document in mongodb, it still contains the dead tag id in the array.

理想情况下,我想懒惰地清理这些引用.有没有人知道这样做的好策略?

Ideally, I would like to clean these references up lazily. Does anyone know of a good strategy to do this?

推荐答案

我试图找到一些内置的方法来做到这一点,但似乎 mongoose 没有提供这样的功能.

I've tried to find some built-in way to do that but seems that mongoose doesn't provide such functionality.

所以我做了这样的事情

User.findById(userId)
    .populate('tags')
    .exec((err, user) => {
        user.tags = user.tags.filter(tag => tag != null);

        res.send(user); // Return result as soon as you can
        user.save(); // Save user without dead refs to database
    })

这样每次获取用户时,您也会从文档中删除无效引用.此外,如果没有删除的引用,您可以创建 isUpdated 布尔变量以不调用 user.save.

This way every time you fetch user you also delete dead refs from the document. Also, you can create isUpdated boolean variable to not call user.save if there was no deleted refs.

const lengthBeforeFilter = user.tags.length;
let isUpdated = user.tags.length;

user.tags = user.tags.filter(tag => tag != null);
isUpdated = lengthBeforeFilter > user.tags.length;

res.send(user);

if (isUpdated) {
    user.save();
}

这篇关于使用 Mongoose populate() 清理死引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆