简体   繁体   中英

How to save multiple refs to other documents in MongoDB using Mongoose?

I am trying to find out the way how I could save multiple references to other documents in MongoDB using Mongoose. Is not a big deal to save one reference to other document, but it gets quickly complicated when you want to save multiple references to other documents and populate them later.

Let's look at what I have:

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);
            })
        })

    }
})

In this example I am saving reviewItem with reference to it in bookItem , but I would like to save an array of reviewItem objects with array of references in bookItem . How I could do that?

The result I am expecting when Book is populated:

[
  {
    "_id": "547b1a4685207124a085d0c5",
    "title": "The Enterprise And Scrum",
    "reviews": [
      {
        "_id": "547b1a4685207124a085d0c3",
        "body": "review 1"
      },
      {
        "_id": "543d99564d01f3de94655ba2",
        "body": "review 2"
      },
      {
        "_id": "543d995625755d19ba72863d",
        "body": "review 3"
      }
    ]
  }
]

You've got to use book.reviews.push. Here is a working example:

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);
}

You have to push the newly added review to reviews array of bookItem bookItem.reiews . Simply try something like this,

 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); }) }) } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM