用猫鼬和nodejs保存另一个文档



我是新来的使用mongodb,我正在练习参考和填充...但是我有一个愚蠢的问题。

我正在从客户那里接收这样的对象。

    {
    "name": "Jhon"
    "books": [
              { 
                "title": "whatever",
                 "pages": 300
              },
              {
                "title": "otherBook",
                 "pages": 450
              }
             ]
    }

所以我有两个模式,作者查理和书籍...所以我假装保存书籍并带上每本书的_id来保存作者。

我在nodejs中的代码

authorCtrl.saveAuthor = (req, res) => {
    var booksId= []
    for (i = 0; i < req.body.books.length; i++) {
        booksModel.create(req.body.books[i], function (err, book) {
            booksId.push(book._id)
        })
    }
    var author= {
        name: req.body.name,
        books: booksId
    }
    console.log(author) // here i check and books array is empty,
    authorModel.create(author).then((authorSaved) => {
        res.json(authorSaved)
    }).catch(err => {
        res.json(err)
    })
}

我知道这是一个异步问题...但是我该怎么做?

//////edit/////////

这是我的模式

作者架构

const mongoose = require('mongoose')
const { Schema } = mongoose;

const authorsSchema = new Schema({
    name: { type: String },
    books: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'books'
    }]
})

module.exports = mongoose.model('authors', authorsSchema);

书籍模式

const mongoose = require('mongoose')
const { Schema } = mongoose;

const booksSchema = new Schema({
    title: { type: String },
    pages: { type: Number }
})

module.exports = mongoose.model('books', booksSchema);

作者schema:

const mongoose = require('mongoose')
const { Schema } = mongoose;
const authorsSchema = new Schema({
    name:  String,
    books: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Book'
    }]
})
module.exports = mongoose.model('Author', authorsSchema);

书籍模式:

const mongoose = require('mongoose')
const { Schema } = mongoose;
const booksSchema = new Schema({
    title: String,
    pages: Number,
})
module.exports = mongoose.model('Book', booksSchema);

nodejs代码:


const author = {
        name: req.body.name
    }
AuthorModel.create(author, (error, createdAuthor)=>{
  //handle error
        BookModel.insertMany(req.body.books, function (err, createdbooks) {
            // handle error
            createdAuthor.books.push(createdbooks); 
            createdAuthor.save();
        })   
}
Try this,
authorCtrl.saveAuthor = (req, res) => {
var booksId= [];
for (var i = req.body.books.length - 1; i >= 0; i--) {
    booksModel.create(req.body.books[i], (err, book) => {
        booksId.push(book._id);
        if(i == 0) { // This if condition executes at the end of the for loop.
            var author= {
                name: req.body.name,
                books: booksId
            };
            console.log(author);
            authorModel.create(author).then((authorSaved) => {
                res.json(authorSaved);
            }).catch(err => {
                res.json(err);
            });
        }
    });
}

}

希望它有帮助...

您可以使用JavaScript承诺进行以下操作:

            var booksId = [];
            var promises = [];
            req.body.books.forEach(element => {
                promises.push(insertBook(element));
            });
            Promise.all(promises)    
            .then(function(data){ 
                /* do stuff when success */
                console.log('##GREAT##',booksId);
                /*** INSERT ARRAY OF BOOK IDs INTO authorModel***/
            })
            .catch(function(err){ 
                /* error handling */ 
            });
            function insertBook(element){
                return new Promise(function(resolve, reject){
                    var book = new booksModel({
                        title: element.title,
                        page:  element.page  
                    });
                    book.save(function(err,data){
                        if(err){
                            console.log(err);
                            reject(err)
                        }else{
                            console.log('#success');
                            booksId.push(data._id)
                            resolve();
                        }
                    });
                });
            }

最新更新