【问题标题】:Nested query in mongoose for checking existence of a value in another collectionmongoose 中的嵌套查询,用于检查另一个集合中是否存在值
【发布时间】:2015-07-29 05:44:55
【问题描述】:

在带有MongooseNode.js 应用程序中,我有两个集合,UsersBooks

用户架构:

var schema = new mongoose.Schema({
    user_name: String,
    user_family: String,
    has_book: { type: Boolean, default: false }
});

这是图书架构:

var schema = new mongoose.Schema({
    book_name: String,
    book_user: String //contains id of a single user
});

我想获取所有用户,如果每个用户在 Book 集合中都有一本书,那么该用户的 has_book 字段填充为 true。我想我需要一个嵌套查询。一个用于获取所有用户,一个用于为每个用户检查该书的存在。如何编写嵌套查询?

我写这个:

User.find().sort("-_id").limit(5).exec(
    function(err, results) {
        if (err) {
            throw err;
        }
        var userID = socket.request.session.passport.user;
        if(userID){
            //check for existence of a book belongs to each user
            // if exist, has_book field of User schema should be turn to true
        }
         return result //main result array after two queries
    }
);

我无法为我需要的第二步完成此代码。

【问题讨论】:

  • 如果没有callback,你是如何使用return data的,通常你可以在User查询中编写嵌套查询。
  • @greenlikeorange:我没看懂,你能给我举个例子吗?
  • 好的,您评论了“两次查询后的主要结果数组”return result,猫鼬的查询是异步的,您可能必须在其中使用这些结果并进行一些回调。例如:callback(result) return result 的实例
  • @greenlikeorange:谢谢。但你对我的主要问题有任何想法吗?可以检查其他集合中每个文档的值的嵌套查询?与关系数据库不同,它在 Mongodb 中非常令人困惑。我需要它,但我找不到任何方法

标签: javascript node.js mongodb mongoose


【解决方案1】:

我认为您只需要在用户架构中保存书籍 ID。

但是如果你不能自定义数据库做隐性函数调用

function checkForBook(users, callback, _results) {
  _results = _results || [];

  if(users.length < 1)
    callback(null, _results);

  var user = user.shift();
  Book.count({book_user: user._id}, function(err, bookCount){
    if(err)
      return callback(err);

    user.has_book = true;
    _results.push(user);

    checkForBook(users, callback, _results);
  });

}

User.find().exce(function(err, usersData){
  checkForBook(usersData, function(err, usersData){
    if(err)
      // do error handle
    else
      // do you favor 
  });
});

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2015-02-13
    • 1970-01-01
    • 2012-11-06
    • 2021-10-27
    • 2021-06-08
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多