我们可以在mongo中使用哪种字段类型来存储对象数组?我想在下面存储数据。我在下面实现了我,并且我添加了代码,也许您可以以某种方式对其进行检查,并让我知道发生问题或错误的部分在哪里。我还提供了示例数据。当前实现的问题是它不会将datas中的books数组中的数据保存为0个元素
{
"books":
[
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
"edition": 3,
"year": 2011
},
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C.Zakas"
],
"edition": 2,
"year": 2009
}
]
}
#implementation
const schema = new Schema({
books: [{ type: mongoose.Schema.Types.Mixed }]
})
var RouterData = mongoose.model('RouterData', schema);
var routerData = {
"books":
[
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
"edition": 3,
"year": 2011
},
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C.Zakas"
],
"edition": 2,
"year": 2009
}
]
}
var data = new RouterData({routerData: routerData});
data.save();
答案 0 :(得分:0)
我认为您可以像这样定义架构。
const booksSchema = new Schema({
books: [{
title: String,
authors: [String],
edition: Number,
year: { type: Date }
}]
})
答案 1 :(得分:0)
用猫鼬定义您的架构,如下所示:
componentDidMount() {
const { location } = this.props;
if (location.state) {
this.setState({ data: location.state.data });
}
}
答案 2 :(得分:0)
如果您使用猫鼬,那么您应该按照自己的模式进行操作
books: [{ type: mongoose.Schema.Types.Mixed }]
mixed表示它可以接受任何对象,数组等。您可以检查https://mongoosejs.com/docs/schematypes.html#mixed
答案 3 :(得分:0)
这应该有效:
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
title: { type: String },
authors: [String],
edition: { type: Number },
year: { type: Number },
});
const MySchema = new mongoose.Schema({
books: [BookSchema],
});
module.exports = mongoose.model('MySchema', MySchema);