添加对象类型为的新mongoDB文档



我对mongoDB完全陌生,只是来自MySQL,所以我试图在Node.js中向mongo数据库添加一个新文档,我的代码可以工作,除非我必须包含一个自定义对象。

这是我的代码:

router.post('/', async (req, res) => {
const book= new Book({
title: req.body.book.title,
year_published: req.body.book.year_published,
author: req.body.author    // ==> here is the problem without it works fine (comes the full author via body parameter)
});
try {
const savedBook = await book.save();

res.json({
insertedBook: savedBook
});
} catch (err) {
//console.log("Error:" + err);

res.json({error: err});
}
});

书籍和作者模型(简化(:

// ======= AUTHORS ================ //
var mongoose         = require('mongoose');
var mongoosePaginate = require('mongoose-paginate-v2');     

const schema = new mongoose.Schema({
name: {
type: String,
required:true
},
place_birth: {
type: String,
required:true}, 

});

schema.plugin(mongoosePaginate);

const Authors = mongoose.model('Authors',schema);

module.exports = Authors;
// ======= BOOKS ================ //
var mongoose         = require('mongoose');
var mongoosePaginate = require('mongoose-paginate-v2');     

var ObjectId = mongoose.Schema.Types.ObjectId;

const schema = new mongoose.Schema({
title: {
type: String,
required:true
},
year_published: {
type: String,
required:true}, 
author: [{
type: ObjectId,
ref: 'Authors', 
required:false
}],
});

schema.plugin(mongoosePaginate);

const Books = mongoose.model('Books',schema);

module.exports = Books;

数据发布:

{
"book": {
"title": "Entrada con cuernos",
"year_published": "2020",
},
"author": {
"name": "Marcus", 
"place_birth": "Moscow",
}
}

插入图书文档的正确方法是什么?

感谢

创建新的Book时,Book.author应该是mongoose文档,这意味着Author应该已经存在于mongoDB中。

您需要首先将Author保存在DB中,然后将其传递到Boot.author中,并使用其Author._id属性集

附言:在描述你的收藏时使用单数:

const Authors = mongoose.model('Authors',schema);
const Authors = mongoose.model('Author',schema); // recommended

猫鼬将负责的复数命名

第一个参数是您的模型所针对的集合的单数名称。Mongoose会自动查找您的型号名称的复数、小写版本

最新更新