Mongoose 的带有 $or 条件的 find 方法无法正常工作

发布于 2024-12-04 02:33:16 字数 557 浏览 0 评论 0原文

最近我开始在 Nodejs 上使用 MongoDB 和 Mongoose。

当我将 Model.find 方法与 $or 条件和 _id 字段一起使用时,Mongoose 无法正常工作。

这不起作用:

User.find({
  $or: [
    { '_id': param },
    { 'name': param },
    { 'nickname': param }
  ]
}, function(err, docs) {
   if(!err) res.send(docs);
});

顺便说一句,如果我删除“_id”部分,这确实起作用!

User.find({
  $or: [
    { 'name': param },
    { 'nickname': param }
  ]
}, function(err, docs) {
   if(!err) res.send(docs);
});

在 MongoDB shell 中,两者都可以正常工作。

Recently I start using MongoDB with Mongoose on Nodejs.

When I use Model.find method with $or condition and _id field, Mongoose does not work properly.

This does not work:

User.find({
  $or: [
    { '_id': param },
    { 'name': param },
    { 'nickname': param }
  ]
}, function(err, docs) {
   if(!err) res.send(docs);
});

By the way, if I remove the '_id' part, this DOES work!

User.find({
  $or: [
    { 'name': param },
    { 'nickname': param }
  ]
}, function(err, docs) {
   if(!err) res.send(docs);
});

And in MongoDB shell, both work properly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

初与友歌 2024-12-11 02:33:16

我通过谷歌解决了这个问题:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
  function(err,docs){
    if(!err) res.send(docs);
});

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
  function(err,docs){
    if(!err) res.send(docs);
});
您的好友蓝忘机已上羡 2024-12-11 02:33:16

我恳请大家使用 Mongoose 的查询构建器语言和承诺而不是回调:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

阅读有关 Mongoose 查询 的更多信息。

I implore everyone to use Mongoose's query builder language and promises instead of callbacks:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

Read more about Mongoose Queries.

別甾虛僞 2024-12-11 02:33:16

您还可以混合添加 $orand 来为您的函数提供更多灵活性、选项和稳健性,如下所示:

var ObjectId = require("mongoose").Types.ObjectId;
var idParam = new ObjectId(param.length < 12 ? "123456789012" : param);
const {nameParam, nicknameParam, ageParam} = req.params || req.body || req.query

User.find({
        $or: [{
                _id: objId
            },
            {
                name: nameParam
            },
            {
                nickname: nicknameParam
            }
        ],
        $and: [{
            age: ageParam
        }]
    },
    function (err, docs) {
        if (!err) res.send(docs);
    }
);

因此,这意味着您的 find() 将查找 (_id = idParam OR name = nameParam ORnickname =nicknameParam) AND (age = AgeParam) 的所有用户,

我希望这对那里的人有帮助。
干杯!!!

You can also add a mix of $or and and to give your functions more flexibility, options and robustness, like so:

var ObjectId = require("mongoose").Types.ObjectId;
var idParam = new ObjectId(param.length < 12 ? "123456789012" : param);
const {nameParam, nicknameParam, ageParam} = req.params || req.body || req.query

User.find({
        $or: [{
                _id: objId
            },
            {
                name: nameParam
            },
            {
                nickname: nicknameParam
            }
        ],
        $and: [{
            age: ageParam
        }]
    },
    function (err, docs) {
        if (!err) res.send(docs);
    }
);

So this means that your find() will look for all users where (_id = idParam OR name = nameParam OR nickname = nicknameParam) AND (age = ageParam)

I hope this helps someone out there.
Cheers!!!

网白 2024-12-11 02:33:16
router.get("/filter", async (req, res) => {
  const filter = req.query.filter || "";
  const users = await User.find({
    $or: [{ firstName: { $regex: filter } }, { lastName: { $regex: filter } }],
  });
  res.json({
    users: users
  });
});

router.get("/filter", async (req, res) => {
  const filter = req.query.filter || "";
  const users = await User.find({
    $or: [{ firstName: { $regex: filter } }, { lastName: { $regex: filter } }],
  });
  res.json({
    users: users
  });
});

妥活 2024-12-11 02:33:16
router.get("/bulk", async (req, res) => {
    const filter = req.query.filter || "";

    const users = await User.find({
        $or: [
                {
                   firstName: { "$regex": filter }
                },
                {
                   lastName: { "$regex": filter }
                }
             ]
    })

    res.json({
        user: users.map(user => ({
            username: user.username,
            firstName: user.firstName,
            lastName: user.lastName,
            _id: user._id
        }))
    })
})
router.get("/bulk", async (req, res) => {
    const filter = req.query.filter || "";

    const users = await User.find({
        $or: [
                {
                   firstName: { "$regex": filter }
                },
                {
                   lastName: { "$regex": filter }
                }
             ]
    })

    res.json({
        user: users.map(user => ({
            username: user.username,
            firstName: user.firstName,
            lastName: user.lastName,
            _id: user._id
        }))
    })
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文