【问题标题】:mongoDB $nin does not work how it shouldmongoDB $nin 无法正常工作
【发布时间】:2018-03-10 01:17:24
【问题描述】:

我正在尝试设计一个社交网络,我有一个 User 架构,其中包含一个字符串数组 user.friends_list。当我运行代码时,结果不是我所期望的。它还给了我friends_list 上的一些成员。

user.friends_list 很好,当我在 mongo shell 中运行查询时,我看到朋友列表正是它应该是的。

module.exports.getMembersWithouFriends = function(user, callback) {
    User.find({ username: { $nin: user.friends_list } }, callback)
}

Mongo Shell

> db.users.find({'username':'mm'}).pretty()
{
        "_id" : ObjectId("59cc1abbf8362823385cb2a9"),
        "first_name" : "mm",
        "last_name" : "mm",
        "email" : "mm@mm.com",
        "username" : "mm",
        "password" : 
        "posts" : [ ],
        "friends_list" : [
                "roy",
                "david",
                "rr",
                "dd",
                "shahar",
                "mm"
        ],
        "__v" : 0
}

当我控制台记录我从 mongo 得到的结果时,我得到了“roy”和“david”。

【问题讨论】:

  • 你的意思是db.users.find({ username: { $nin: ["roy", "david"]} } 不工作?它返回带有“roy”和“david”的文档?
  • no .. 我的意思是 User.find({ username: { $nin: user.friends_list } }, callback) 返回一个包含“roy”和“david”的文档,但是如果我使用 Mongo Shell 它确实可以正常工作
  • 尝试使用user.friends_list.map(x => String(x))
  • @GrégoryNEUT 我已经尝试过了,但我得到了相同的结果。谢谢

标签: node.js mongodb mongoose mongodb-query social-networking


【解决方案1】:

看来这段代码运行良好,问题出在我的数据库中。我有一些不存在的用户仍在用户数据库中。

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 2023-03-29
    • 2020-10-20
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多