2017-10-15 20 views
5

Để dành thời gian giải thích những gì đang diễn ra từ đầu đến cuối.điền vào những người dùng sau mongoose

Preamble:

Một người sử dụng một sau 10 người khác. Khi người dùng A đăng nhập, một số lượng bài đăng X từ mỗi người trong số 10 người được đưa vào xem.

Tôi không biết đó có phải là điều đúng hay không và sẽ đánh giá cao cách tốt hơn để thực hiện. Tuy nhiên, tôi muốn thử, và nó không hoạt động.

Thực hiện theo mẫu:

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

let FollowSchema = new Schema({ 
    user: { 
    type: Schema.Types.ObjectId, 
    ref: 'User' 
    }, 
    followers: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Card' 
    }], 
    following: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Card' 
    }] 
}); 

module.exports = mongoose.model('Follow', FollowSchema); 

Thẻ Mẫu

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

let CardSchema = new Schema({ 
    title: String, 
    content: String, 
    createdById: { 
    type: Schema.Types.ObjectId, 
    ref: 'User' 
    }, 
    createdBy: { 
    type: String 
    } 
}); 

module.exports = mongoose.model('Card', CardSchema); 

Thực hiện theo lôgic

Khi người dùng A sau sử dụng B, làm hai việc:

  • Đẩy user_id của B để sử dụng Một tài liệu về lĩnh vực 'theo dõi' (A đang theo B)
  • Đẩy user_id của A để sử dụng tài liệu B vào 'tín đồ' trường (B Tiếp theo là A)

    router.post('/follow', utils.loginRequired, function(req, res) { 
    const user_id = req.user._id; 
    const follow = req.body.follow_id; 
    
    let bulk = Follow.collection.initializeUnorderedBulkOp(); 
    
    bulk.find({ 'user': Types.ObjectId(user_id) }).upsert().updateOne({ 
        $addToSet: { 
         following: Types.ObjectId(follow) 
        } 
    }); 
    
    bulk.find({ 'user': Types.ObjectId(follow) }).upsert().updateOne({ 
        $addToSet: { 
         followers: Types.ObjectId(user_id) 
        } 
    }) 
    
    bulk.execute(function(err, doc) { 
        if (err) { 
         return res.json({ 
          'state': false, 
          'msg': err 
         }) 
        } 
        res.json({ 
         'state': true, 
         'msg': 'Followed' 
        }) 
    }) 
    

    })

thực tế DB đánh giá cao

> db.follows.find().pretty() 
{ 
    "_id" : ObjectId("59e3e27dace1f14e0a70862d"), 
    "user" : ObjectId("59e2194177cae833894c9956"), 
    "following" : [ 
     ObjectId("59e3e618ace1f14e0a708713") 
    ] 
} 
{ 
    "_id" : ObjectId("59e3e27dace1f14e0a70862e"), 
    "user" : ObjectId("59e13b2dca5652efc4ca2cf5"), 
    "followers" : [ 
     ObjectId("59e2194177cae833894c9956"), 
     ObjectId("59e13b2d27cfed535928c0e7"), 
     ObjectId("59e3e617149f0a3f1281e849") 
    ] 
} 
{ 
    "_id" : ObjectId("59e3e71face1f14e0a708770"), 
    "user" : ObjectId("59e13b2d27cfed535928c0e7"), 
    "following" : [ 
     ObjectId("59e3e618ace1f14e0a708713"), 
     ObjectId("59e13b2dca5652efc4ca2cf5"), 
     ObjectId("59e21942ca5652efc4ca30ab") 
    ] 
} 
{ 
    "_id" : ObjectId("59e3e71face1f14e0a708771"), 
    "user" : ObjectId("59e3e618ace1f14e0a708713"), 
    "followers" : [ 
     ObjectId("59e13b2d27cfed535928c0e7"), 
     ObjectId("59e2194177cae833894c9956") 
    ] 
} 
{ 
    "_id" : ObjectId("59e3e72bace1f14e0a708779"), 
    "user" : ObjectId("59e21942ca5652efc4ca30ab"), 
    "followers" : [ 
     ObjectId("59e13b2d27cfed535928c0e7"), 
     ObjectId("59e2194177cae833894c9956"), 
     ObjectId("59e3e617149f0a3f1281e849") 
    ] 
} 
{ 
    "_id" : ObjectId("59f0eef155ee5a5897e1a66d"), 
    "user" : ObjectId("59e3e617149f0a3f1281e849"), 
    "following" : [ 
     ObjectId("59e21942ca5652efc4ca30ab"), 
     ObjectId("59e13b2dca5652efc4ca2cf5") 
    ] 
} 
> 

Với những kết quả cơ sở dữ liệu ở trên, đây là câu hỏi của tôi:

Query

router.get('/follow/list', utils.loginRequired, function(req, res) { 
    const user_id = req.user._id; 

    Follow.findOne({ 'user': Types.ObjectId(user_id) }) 
     .populate('following') 
     .exec(function(err, doc) { 
      if (err) { 
       return res.json({ 
        'state': false, 
        'msg': err 
       }) 
      }; 

      console.log(doc.username); 

      res.json({ 
       'state': true, 
       'msg': 'Follow list', 
       'doc': doc 
      }) 
     }) 
}); 

Với các truy vấn trên, từ sự hiểu biết nhỏ của tôi của Mongoose cư, tôi hy vọng sẽ nhận được thẻ từ mỗi Người dùng trong mảng following.

Sự hiểu biết và kỳ vọng của tôi có thể sai, tuy nhiên với một endgoal như vậy, cách tiếp cận dân cư này có được không? Hay tôi đang cố gắng giải quyết một nhiệm vụ tổng hợp với dân số?

UPDATE:

Cảm ơn cho câu trả lời. Bắt khá gần, nhưng vẫn còn, mảng followingCards không chứa kết quả.Dưới đây là nội dung của hiện tại Follow mô hình của tôi:

> db.follows.find().pretty() 
{ 
    "_id" : ObjectId("59f24c0555ee5a5897e1b23d"), 
    "user" : ObjectId("59f24bda1d048d1edad4bda8"), 
    "following" : [ 
     ObjectId("59f24b3a55ee5a5897e1b1ec"), 
     ObjectId("59f24bda55ee5a5897e1b22c") 
    ] 
} 
{ 
    "_id" : ObjectId("59f24c0555ee5a5897e1b23e"), 
    "user" : ObjectId("59f24b3a55ee5a5897e1b1ec"), 
    "followers" : [ 
     ObjectId("59f24bda1d048d1edad4bda8") 
    ] 
} 
{ 
    "_id" : ObjectId("59f24c8855ee5a5897e1b292"), 
    "user" : ObjectId("59f24bda55ee5a5897e1b22c"), 
    "followers" : [ 
     ObjectId("59f24bda1d048d1edad4bda8") 
    ] 
} 
> 

Dưới đây là tất cả các nội dung hiện tại tôi có từ Card mẫu:

> db.cards.find().pretty() 
{ 
    "_id" : ObjectId("59f24bc01d048d1edad4bda6"), 
    "title" : "A day or two with Hubtel's HTTP API", 
    "content" : "a day or two", 
    "external" : "", 
    "slug" : "a-day-or-two-with-hubtels-http-api-df77056d", 
    "createdBy" : "seanmavley", 
    "createdById" : ObjectId("59f24b391d048d1edad4bda5"), 
    "createdAt" : ISODate("2017-10-26T20:55:28.293Z"), 
    "__v" : 0 
} 
{ 
    "_id" : ObjectId("59f24c5f1d048d1edad4bda9"), 
    "title" : "US couple stole goods worth $1.2m from Amazon", 
    "content" : "for what", 
    "external" : "https://bbc.com", 
    "slug" : "us-couple-stole-goods-worth-dollar12m-from-amazon-49b0a524", 
    "createdBy" : "nkansahrexford", 
    "createdById" : ObjectId("59f24bda1d048d1edad4bda8"), 
    "createdAt" : ISODate("2017-10-26T20:58:07.793Z"), 
    "__v" : 0 
} 

Với cư ảo ví dụ từ bạn (@Veeram), đây là phản ứng Tôi nhận được:

{"state":true,"msg":"Follow list","doc":{"_id":"59f24c0555ee5a5897e1b23d","user":"59f24bda1d048d1edad4bda8","following":["59f24b3a55ee5a5897e1b1ec","59f24bda55ee5a5897e1b22c"],"followers":[],"id":"59f24c0555ee5a5897e1b23d","followingCards":[]}} 

Mảng followingCards trống.

Sử dụng truy vấn $lookup mặt khác chỉ đơn giản trả []

Tôi có thể thiếu cái gì?

+0

Chỉnh sửa câu hỏi của bạn với schemas của bạn. – Mikey

+0

@JohnnyHK ok. sẽ làm. – Rexford

+0

điền chỉ hoạt động nếu bạn đẩy refs để Follow.following trước khi lưu! –

Trả lời

2

Bạn có thể sử dụng dân cư ảo hoặc $lookup nhà điều hành trong đường ống tổng hợp.

Sử dụng ảo cư

FollowSchema.virtual('followingCards', { 
    ref: 'Card', 
    localField: 'following', 
    foreignField: 'createdById' 
}); 

Follow.findOne({ 
    'user': Types.ObjectId(user_id) }) 
    .populate('followingCards') 
    .exec(function(err, doc) {  
     console.log(JSON.stringify(doc)); 
}); 

Sử dụng $lookup hợp

Follow.aggregate([ 
    { 
    "$match": { 
     "user": Types.ObjectId(user_id) 
    } 
    }, 
    { 
    "$lookup": { 
     "from": "cards", 
     "localField": "following", 
     "foreignField": "createdById", 
     "as": "followingCards" 
    } 
    } 
]).exec(function (err, doc) { 
    console.log(JSON.stringify(doc)); 
}) 
+0

Cảm ơn bạn đã phản hồi. Đã thử cách tiếp cận của bạn. Mảng 'followingCards' là một phần của đối tượng phản hồi, tuy nhiên mảng chứa danh sách trống. Vui lòng xem câu hỏi được cập nhật cho các giá trị thực tế trong DB hiện tại. – Rexford

+0

Np. Bạn có thể thêm 'mongoose.set ('debug', true);' ở đầu tệp để xem truy vấn nào được gửi tới mongodb không? Btw Tôi đã sửa chữa tra cứu để bao gồm tên bộ sưu tập chính xác 'thẻ'. Bạn cũng có thể thử tra cứu tổng hợp mà không có giai đoạn phù hợp để kiểm tra xem nó hoạt động và sau đó bạn có thể đặt nó trở lại? – Veeram

+0

Giá trị trường mảng 'sau' trong bộ sưu tập' theo sau' không có 'createdById' khớp trong' colleciton 'thẻ. Hãy thử sử dụng trường 'người theo dõi' thay cho dữ liệu mà bạn đã cung cấp và bạn có thể điều chỉnh câu trả lời một cách thích hợp. – Veeram

0
var mongoose = require('mongoose'), Schema = mongoose.Schema 

var eventSchema = Schema({ 
title  : String, 
location : String, 
startDate : Date, 
endDate : Date 
}); 

var personSchema = Schema({ 
firstname: String, 
lastname: String, 
email: String, 
dob: Date, 
city: String, 
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }] 
}); 

var Event = mongoose.model('Event', eventSchema); 
var Person = mongoose.model('Person', personSchema); 

Để hiển thị populate được sử dụng như thế nào, đầu tiên tạo ra một đối tượng người,

aaron = new Person({firstname: 'Aaron'}) and an event object, 
    event1 = new Event({title: 'Hackathon', location: 'foo'}): 

    aaron.eventsAttended.push(event1); 
    aaron.save(callback); 

Sau đó, khi bạn thực hiện truy vấn của bạn, bạn có thể cư tài liệu tham khảo như thế này:

Person 
.findOne({ firstname: 'Aaron' }) 
.populate('eventsAttended') .exec(function(err, person) { 
if (err) return handleError(err); 
console.log(person); 
}); 

// chỉ hoạt động nếu chúng tôi đã đẩy refs tới person.eventsAttended

Các vấn đề liên quan