推广一波我写的 Nodejs Mongoose 插件,mongoose-find-by-reference

https://github.com/cheezone/mongoose-find-by-reference

相信不少使用 Mongoose 的朋友都遇到过,想要在对参考字段的值进行搜索。

参考字段,也就是类似这样的字段:

{
    type: MongooseSchema.Types.ObjectId,
    ref: 'XXX',
}

例如我们有 Cat 这个 Model ,它有 sex (性别)、parents (父母)和 owner (主人)三个属性,ref 分别是 'Cat' 和 'Person'; Person 则有 name (名字)一个属性。

然后我们想要查询性别为女、父母的主人名字是 'Dean' 的猫,我们可能会这么写:

const result = await catModel
  .find({
    $and: {
      parents: {
        'owner.name': 'Dean',
      },
      sex: 0,
    },
  })
  .exec();

但我们知道,这样只会报错。因为 parents 此刻是 ObjectId ,populate 是 Mongoose 的功能,不是 MongoDB 的。

假设使用 MongoDB 的 $lookup 呢,又麻烦,又丧失了 Mongoose 的不少便捷功能。

假设构建一个 method ,手动把搜索条件替换成符合搜索条件的 ObjectId 数组,又得特事特办,很麻烦。

所以,不如现在来使用 MongooseFindByReference 模块,它会自动把对参考字段的搜索,替换成符合搜索条件的 ObjectId 数组。

使用后,搜索条件就会被替换成:

const oldConditions = {
    $and: {
      parents: {
        'owner.name': 'Dean',
      },
      sex: 0,
    },
  };

const newConditions = { $and: { parents: { $in: [/* 符合条件的猫的 ObjectId 数组 */], }, sex: 0, }, };

欢迎下载,欢迎给 Star 嘿嘿

npm i mongoose-find-by-reference

推广一波我写的 Nodejs Mongoose 插件,mongoose-find-by-reference

1 回复

当然,很高兴能帮助你推广你的 Node.js Mongoose 插件 mongoose-find-by-reference。这个插件听起来非常有用,特别是对于那些需要通过引用字段高效查询 MongoDB 文档的开发人员。

下面是一个简单的示例,展示如何使用你的插件来查找引用其他集合的文档。

首先,确保你已经安装了 mongoose 和你的插件:

npm install mongoose mongoose-find-by-reference

然后,假设我们有两个模型 UserPost,其中 Post 引用 User

const mongoose = require('mongoose');
const findByReference = require('mongoose-find-by-reference')(mongoose);

const userSchema = new mongoose.Schema({ name: String });
const postSchema = new mongoose.Schema({
  content: String,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

userSchema.plugin(findByReference, { referenceIn: 'Post.user' });
postSchema.plugin(findByReference);

const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);

现在,你可以通过引用字段查找 Post

User.findByIdAndFindByReference('userId', 'Post', (err, posts) => {
  if (err) return handleError(err);
  console.log(posts); // 输出所有引用该用户的帖子
});

这个示例展示了如何设置并使用你的插件来简化通过引用字段的查询。希望这个示例能帮助潜在用户更好地理解你的插件的功能!

回到顶部