如何在嵌套对象属性上使用 MongoDB $ne [英] How to use MongoDB $ne on nested object property

查看:62
本文介绍了如何在嵌套对象属性上使用 MongoDB $ne的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 mongoose 连接到 mongoDB 的节点 API.我正在创建一个基于 Brad Traversy 课程 Node.js API Masterclass With Express &MongoDB.这一切都很好.

I have a node API which connects to a mongoDB through mongoose. I am creating an advanced results middleware that enabled selecting, filtering, sorting, pagination etc. based on a Brad Traversy course Node.js API Masterclass With Express & MongoDB. This is all good.

我正在修改课程中的代码,以便能够使用 $ne(不等于)运算符,并且我希望能够获得一个不等于模型的嵌套属性(用户 ID)的模型.我将其用于探索功能以查看事物列表,但我不想向用户展示他们自己的事物.我无法弄清楚如何访问 id 属性.

I am adapting the code from the course to be able to use the $ne (not equal) operator and I want to be able to get a model that is not equal to a nested property (user id) of the model. I am using this for an explore feature to see a list of things, but I don't want to show the user their own things. I am having trouble figuring out how to access the id property.

************************ 更新************************

********************* UPDATE *********************

似乎我读过的所有文档都建议像这样编写 const 注入:

It seems all the documentation I've read recommends writing const injected like this:

const injected = {
  'user._id': { "$ne": req.user.id }
};

但由于某种原因它不起作用.我可以查询只是一个普通字符串值的顶级属性,如下所示:

but for some reason it is not working. I can query top level properties that are just a plain string value like this:

const injected = {
  access: { "$ne": "public" }
};

但不是对象的属性.有谁知道为什么?是不是因为我要查询的属性是一个id?我也试过:

but not a property on an object. Does anyone know why? Is it because the property I want to query is an id? I've also tried:

const injected = {
  'user._id': { "$ne": mongoose.Types.ObjectId(req.user.id) }
};

这也不起作用...

所以模型看起来像这样:

So the model looks like this:

{
  name: 'Awesome post',
  access: 'public',
  user: {
    _id: '2425635463456241345', // property I want to access
  }
}

然后实际的高级结果中间件看起来像这样,它是我试图访问 id 的注入"对象.在课程中,布拉德使用这种语法来使用 lte (/?averageCost[lte]=10000) 但我的 ne 没有得到任何结果.有人可以帮我吗?

then the actual advanced results middleware looks like this and it's the 'injected' object where I am trying to access id. In the course brad uses this syntax to use lte (/?averageCost[lte]=10000) but I do not get any results with my ne. Can anyone help me here?

const advancedResults = (model, populate) => async (req, res, next) => {
  let query;

  const injected = {
      access: 'public',
      'user._id[ne]': req.user.id,  // I don't think user._id[ne] is correct
    };
  }

  // Copy req.query
  const reqQuery = { ...req.query, ...injected };

  console.log('injected: ', injected);


  // Fields to exclude
  const removeFields = ['select', 'sort', 'page', 'limit'];

  // Loop over removeFields and delete them from reqQuery
  removeFields.forEach(param => delete reqQuery[param]);

  // Create query string
  let queryStr = JSON.stringify(reqQuery);

  // Create operators ($gt, $gte, etc)
  queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in|ne)\b/g, match => `$${match}`);


  // Finding resource and remove version
  query = model.find(JSON.parse(queryStr)).select('-__v');

  // Select Fields
  if (req.query.select) {
    const fields = req.query.select.split(',').join(' ');
    query = query.select(fields);
  }

  // Sort
  if (req.query.sort) {
    const sortBy = req.query.sort.split(',').join(' ');
    query = query.sort(sortBy);
  } else {
    query = query.sort('-createdAt');
  }

  // Pagination
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 25;
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const total = await model.countDocuments(JSON.parse(queryStr));

  query = query.skip(startIndex).limit(limit);

  if (populate) {
    query = query.populate(populate);
  }

  // Executing query
  const results = await query;

  // Pagination result
  const pagination = {};

  if (endIndex < total) {
    pagination.next = {
      page: page + 1,
      limit,
    };
  }

  if (startIndex > 0) {
    pagination.prev = {
      page: page - 1,
      limit,
    };
  }

  res.advancedResults = {
    success: true,
    count: results.length,
    pagination,
    data: results,
  };

  next();
};

module.exports = advancedResults;

推荐答案

回答您关于如何使用 $ne 的问题:

Answering your question about how to use $ne:

$ne如下:

"field":{
  "$ne": yourValue
}

进入你的查询应该是这样的:

Into your query should be like:

"user._id": {
  "$ne": req.user.id
}

示例此处

$ne 运算符将返回字段值与给定值不匹配的所有文档.

$ne operator will return all document where the field value don't match with the given value.

正如您所做的那样,访问嵌套字段必须使用点符号.

As you have done, to acces the nested field is necessary use the dot notation.

此外,为了确保它有效,如果您的架构将 _id 定义为 ObjectId,则可能需要将 req.user.id 解析为 ObjectId.
但是如果在您的架构中是一个字符串,那么应该可以工作.

Also, to ensure it works, if your schema defines _id as ObjectId maybe is necessary parse req.user.id to ObjectId.
But if in your schema is a string then should works.

所以尝试(根本没有测试):

So try (not tested at all):

const injected = {
  'user._id': { "$ne": req.user.id }
};

这篇关于如何在嵌套对象属性上使用 MongoDB $ne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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