簡體   English   中英

貓鼬:合並兩個互相引用的文檔

[英]Mongoose: Merging two documents that reference each other

我目前正在嘗試從關系數據庫背景學習如何使用NoSQL。 在這個項目中,我將Express與Mongoose結合使用。

當我嘗試將兩個相互引用的模型合並在一起時,我在回調方面苦苦掙扎。 我正在嘗試編輯一個模型(Ribbits)組中的每個項目,以包含另一個模型(發布了Ribbit的用戶)的屬性。 因為查找與Ribbit關聯的User的調用是異步的,所以我無法返回已編輯Ribbits的集合(帶有用戶信息)。

在我的網站上,我擁有屬於用戶的ribbit(又稱tweets)。 用戶可以有很多肋骨。 在我的頁面之一中,我想列出該服務上的所有ribbit,以及與發布該ribbit的用戶相關的一些信息。

我發現的一個解決方案是嵌入文檔,但是我發現這僅限於顯示屬於用戶的肋骨。 以我為例,我首先要獲取所有的肋骨,然后再為每個肋骨附加有關誰發布的信息。

理想情況下,我希望我的模式函數返回一個Ribbit對象數組,以便隨后可以在視圖中呈現它。

// models/user.js
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var userSchema = Schema({
  username: String,
  email: String,
  password: String,
  name: String,
  profile: String,
  ribbits: [{
    type: Schema.Types.ObjectId,
    ref: 'Ribbit',
  }]
});

module.exports = mongoose.model('User', userSchema);

// models/ribbit.js
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    User = require('./user');

var ribbitSchema = Schema({
  content:  { type: String, maxlength: 140 },
  created:  { type: Date, default: Date.now() },
  owner:    { type: Schema.Types.ObjectId, ref: 'User' },
});

ribbitSchema.methods.getOwnerObj = function(cb) {
  return User.findOne({ _id: this.owner }, cb);
}

ribbitSchema.statics.getAllRibbits = function(cb) {
  this.find({}, function(err, ribbits) {
    console.log('Before Transform');
    console.log(ribbits);

    ribbits.forEach(function(ribbit) {
      ribbit.getOwnerObj(function(err, owner) {
        ribbit = {
          content: ribbit.content,
          created: ribbit.created,
          owner: {
            username: owner.username,
            email: owner.email,
            name: owner.name,
            profile: owner.profile,
          }
        };
      });
    });
  });
}

module.exports = mongoose.model('Ribbit', ribbitSchema);

如果我理解正確,則可以在這種情況下使用Mongoose 填充方法:

ribbitSchema.statics.getAllRibbits = function(cb) {
  this.find({}).populate('owner').exec(function(err, ribbits){
    console.log(ribbits[0].owner)
    return cb(err, ribbits);
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM