如何使用Mongoose将多个引用保存到MongoDB中的其他文档?

时间:2014-12-02 22:22:35

标签: node.js mongodb reference mongoose populate

我试图找出如何使用Mongoose在MongoDB中保存对其他文档的多个引用的方式。保存对其他文档的引用并不是什么大不了的事,但是当你想要保存对其他文档的多个引用并在以后填充它们时,它会变得很复杂。

让我们来看看我有什么:

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

var Book = Schema({
    title: String,
  reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }]
});

var Review = Schema({
    body: String
});

var Book  = mongoose.model('Book', bookSchema);
var Review = mongoose.model('Book', reviewSchema);

var reviewItem = new Review({body: "review content"});

Book.find({}).exec(function(err, collection) {
    if(collection.length === 0) {

        reviewItem.save(function (err) {
            if (err) return handleError(err);

            var bookItem = new Book({
                title: "book title",
                reviews: reviewItem._id
            });

            bookItem.save(function (err) {
                if (err) return handleError(err);
            })
        })

    }
})

在此示例中,我在reviewItem中引用bookItem保存reviewItem,但我希望在bookItem中保存一组带有引用数组的Book个对象。我怎么能这样做?

填充[ { "_id": "547b1a4685207124a085d0c5", "title": "The Enterprise And Scrum", "reviews": [ { "_id": "547b1a4685207124a085d0c3", "body": "review 1" }, { "_id": "543d99564d01f3de94655ba2", "body": "review 2" }, { "_id": "543d995625755d19ba72863d", "body": "review 3" } ] } ] 时我期待的结果:

{{1}}

2 个答案:

答案 0 :(得分:2)

你必须使用book.reviews.push。这是一个有效的例子:

var async = require('async');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var Review = mongoose.model('Review', {
    body: String
});

var Book = mongoose.model('Book', new Schema({
    title: String,
    reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }]
}));

async.parallel([
    function(next) { Book.remove({}, next); }, 
    function(next) { Review.remove({}, next); }], 
    function() {
        async.map(['review 1', 'review 2', 'review 3'], createReview, function(err, reviews) {
            var book = new Book({ title: 'something clever' });
            for(var i = 0; i < reviews.length; i++) {
                book.reviews.push(reviews[i]);
            }

            book.save(function(err, doc) {
                Book.find({})
                    .populate('reviews')
                    .exec(function (err, books) {
                        console.log(err, books);
                    });
            });
        });     
    });

function createReview(body, fn) {
    var review = new Review({ body: body });
    review.save(fn);
}

答案 1 :(得分:0)

您必须将新添加的评论推送到 bookItem bookItem.reiews 的评论数组。 只需尝试这样的事情,

Book.find({}).exec(function(err, collection) {
  if (collection.length === 0) {

    reviewItem.save(function(err) {
      if (err) return handleError(err);

      var bookItem = new Book({
        title: "book title",
      });

      bookItem.reviews.push(reviewItem)

      bookItem.save(function(err) {
        if (err) return handleError(err);
      })
    })

  }
})