【问题标题】:mongoose findOne with multiple paramters does not work带有多个参数的猫鼬 findOne 不起作用
【发布时间】:2017-08-15 00:11:31
【问题描述】:

我的架构如下图:

itemlike.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const itemLike = new Schema({
    item_id: { type: mongoose.Schema.ObjectId, ref: 'items', index: true },
    no_of_likes: { type: Number, default: 0 },
    users: [{ type: mongoose.Schema.ObjectId, ref: 'user' }]
}, { versionKey: false });


module.exports = mongoose.model('item_like', itemLike);

我的查询如下图:

itemLike.findOne({ 'item_id': itemData.item_id, 'user': userInfo }).then((info) => {
                    if (!info) {
                        let newItem = new itemLike();
                        newItem.no_of_likes = 1;
                        newItem.users.push(userInfo);
                        newItem.save().then((likeInfo) => {
                            res.json({
                                status: '200',
                                message: 'Thanks for appreciating our product',
                                data: likeInfo
                            });
                        }).catch((err) => {
                            console.log("hh " + err);
                            res.json({
                                status: '500',
                                message: 'Oops,something went wrong'
                            });
                        });
                    } else {
                        res.json({
                            status: '200',
                            message: 'you have already liked the product'
                        });
                    }
                }).catch((err) => {
                    console.log("ll " + err);
                    res.json({
                        status: '500',
                        message: 'Oops,something went wrong'
                    });
                });

这里假设我的回复如下:

{
    "status": "200",
    "message": "Thanks for appreciating our product",
    "data": {
        "_id": "5990dd8e669a041fec3aecb9",
        "users": [
            "591325c6b685bc165313a8ff",
            "591325c6b685bc165313a8ef"
        ],
        "no_of_likes": 1
    }
}

现在假设当我使用 item_id: 5990dd8e669a041fec3aecb9users:591325c6b685bc165313a8ef 进行 findOne 查询时,它应该给我准确的文档。但是对于这种情况 findOne 无法找到文档,我认为users 字段是一个参考数组,它不能同时查看两个参数。那么如何实现这个功能呢?

【问题讨论】:

  • 应该是users,而不是user(单个)。
  • 是的,我更改了 users ,但问题仍然存在。为此,我更新了我的问题

标签: node.js mongoose


【解决方案1】:

如果 itemData.item_iduserinfo 都是 ID,那么你会这样做

 itemLike.findOne({ 
     _id: itemData.item_id,
     users: {
         $in: [userInfo]
     }
 }).then(...).catch(...);

您使用$in,因为users 是一个数组。

编辑

查询不起作用,因为您正在寻找item_id,但您的代码中没有任何地方存储item_id

但是,查看您的回复,您会发现您要查找的两个值存储在_idusers 中。因此,如上所示,在您的查询中使用_idusers

【讨论】:

  • $ in 无法在 users 数组中找到 userInfo
猜你喜欢
  • 2015-06-16
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 2012-11-06
  • 1970-01-01
  • 2020-09-04
相关资源
最近更新 更多