node.js - Mongoose 切片数组,在填充字段中

标签 node.js mongodb mongoose

我有以下 mongoose 模式:

主要的是userSchema,它包含了一组 friend , friend 架构。每个 friendSchema 都是一个包含 messageSchema 数组的对象。 messageSchema 是最深的对象,包含消息的主体。

var messageSchema = new mongoose.Schema({
    ...
    body: String
});

var conversationsSchema = new mongoose.Schema({
    ...
    messages: [messageSchema]
});

var friendSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  conversation: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Conversation',
  },
}, { _id : false });


var userSchema = new mongoose.Schema({
    ...
    friends: [friendSchema]
});

当检索特定用户的 friend 时,我会填充其 friend 资料,如果存在对话,我也会填充该对话。 我如何切片 conversations.messages 数组,它位于 conversationobject 的群体中?我不想返回整个消息。

  var userId = req.userid;
  var populateQuery = [{ path:'friends.user', 
                         select: queries.overviewConversationFields },
                       { path:'friends.conversation' }];

  User
  .find({ _id: userId }, { friends: 1 })
  .populate(populateQuery)
  .exec(function(err, result){
    if (err) { next(err); }
    console.log(result);
  }

EDIT(1) :我试过了

  .slice('friends.conversation.messages', -3)

EDIT(2) :我尝试填充查询

  { path:'friends.conversation', options: { 'friends.conversation.messages': { $slice: -2 } }

EDIT(3):目前,我可以实现我想要的,在执行查询后对数组进行切片。这根本没有优化。

最佳答案

一个可行的小解决方法。 我没有找到如何 $slice 驻留在填充字段中的数组。

但是$slice 运算符可以完美地作用于任何数组,只要它的父文档没有被填充。

1) 我决定通过添加一个数组来更新 conversationSchema,其中包含对话中涉及的两个用户的 Id:

var conversationsSchema = new mongoose.Schema({
    users: [type: mongoose.Schema.Types.ObjectId],
    messages: [messageSchema]
});

2) 然后,我可以轻松找到我的用户参与的每个对话。 正如我所说,我可以对 messages 数组进行适当的切片,因为无需填充任何内容。

Conversation.find({ users: userId }, 
                  { 'messages': { $slice: -1 }}, function(err, conversation) {
});

3) 最后,我要做的就是分别查询所有 friend 和对话,然后用一个简单的循环和一个 _find 将所有内容放回一起。 这将执行 或多或少 与 Mongo population

相同的过程

使用 async.parallel 提高效率:

 async.parallel({
      friends: function(done){
        User
          .find({ _id: userId }, { friends: 1 })
          .populate(populateQuery)
          .exec(function(err, result){
          if (err) { return done(err);}
          done(null, result[0].friends);
        });
      },
      conversations: function(done){
        Conversation.find({ users: userId }, { 'messages': { $slice: -1 }}, function(err, conversation) {
          if (err) { return done(err); }
          done(null, conversation)
        });
      }}, function(err, results) {
          if (err) { return next(err); }

          var friends = results.friends;
          var conversations = results.conversations;

          for (var i = 0; i < friends.length; i++) {
            if (friends[i].conversation) {
              friends[i].conversation = _.find(conversations, function(conv){ 
                return conv._id.equals(new ObjectId(friends[i].conversation));
              });
            }
          }

      });
      // Friends contains now every conversation, with the last sent message.

关于node.js - Mongoose 切片数组,在填充字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306586/

相关文章:

javascript - 在 node.js 中验证 JWT

node.js - package.json 依赖部分中的 "npm:"前缀是什么意思?

mysql - 用于前缀搜索的最佳数据库查询

mongodb - Mongoose 的替代品?

javascript - Nodejs&Formidable, 上传图片

node.js - Node - Bluemix 对象存储

java - Morphia 在从实体子类更新字段时更改 className

node.js - 更新 MongoDb 子文档中数组中的特定文档

node.js - Mongoose 使用 presave 中间件推送到数组

Javascript:如何在回调中设置父对象变量