【问题标题】:SailsJS - Mongo find with where or condition Association (one to one)SailsJS - Mongo 查找与位置或条件关联(一对一)
【发布时间】:2016-02-28 05:01:06
【问题描述】:

我有一个模型:

module.exports = {

  schema: true,

  attributes: {

    friend1: {
      model: "User", //Logged in User
      required: true
    },
    friend2: {
      model: "User", //Profile Viewing User to whom I can send friend request
      required: true
    },
    status: {
      type: "int",
      defaultsTo: "0"
    }
  }
};

现在我正在尝试使用以下书面过滤器检查是否有任何用户是我的朋友,似乎它不起作用!

Friend.find().where({
    or: [
        {
            friend1: user_id,
            friend2: fried_id
        },
        {
            friend1: fried_id,
            friend2: user_id
        }
    ]
}).exec(function findCB(err, Friend) {
    if(err) throw err;
    next(Friend);
});

谁能弄清楚我在这里做错了什么?

【问题讨论】:

    标签: node.js mongodb sails.js waterline


    【解决方案1】:

    How to use Search Modifier “OR” in Sails.js using Waterline Adapter for Mongo 存在某种相关的已关闭问题,具体取决于您使用的版本。作为一种解决方法,我只能建议您尝试使用 native() 来访问表示指定模型的原始 Mongo 集合实例,从而允许您执行原始 Mongo 查询:

    var criteria = { 
        "$or": [
            { "friend1": user_id, "friend2": friend_id },
            { "friend1": friend_id, "friend2": user_id }
        ]
    };
    
    // Grab an instance of the mongo-driver
    Friend.native(function(err, collection) {        
        if (err) return res.serverError(err);
    
        // Execute any query that works with the mongo js driver
        collection.find(criteria).toArray(function (err, friendObj) {
            if(err) throw err;
            console.log(friendObj);
        });
    });
    

    【讨论】:

    • np 似乎还有一个问题,当我使用上面的示例时,我得到了一个类似的错误: mongodb\lib\utils.js:98 process.nextTick(function() { throw err; }) ; ^ TypeError: Object [object Object] 没有方法'exec'
    • 我什至还尝试了下面的 toArray 回调似乎这个也不起作用并返回我 []: Friend.native(function(err, collection) { if (err) return res.serverError(err) ; collection.find(criteria).toArray(function (err,friendObj) { if(err) throw err; console.log(friendObj); next(friendObj); }); });
    • 您使用的是什么版本的 Sails?当它工作时,你是如何运行脚本的?
    • 1.我正在使用 v0.11.2 2. 当我使用未定义的 user_id 3. 命令行:sails lift
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多