[英]Storing Javascript Array of Objects in Mongo DB using Mongoose
I have an array of the form [{key: ..., type: ..., value: ...}]
and want to store it in the fields
field in the following schema: 我有一个
[{key: ..., type: ..., value: ...}]
形式的数组,并希望将其存储在以下模式的fields
字段中:
var articleSchema = mongoose.Schema({
name: {
type: String,
unique: true,
required: true
},
updated: {
type: Date,
default: Date.now
},
pageviews: {
type: Number,
default: 0
},
fields: [{
key: String,
type: String,
value: String
}],
image: String
});
I am doing this as follows, my Javascript array referenced as keyValueObj
我这样做如下,我的Javascript数组引用为
keyValueObj
Article.findOneAndUpdate(
{ name: articleName },
{
fields: keyValueObj
},
{ upsert: true },
callback
);
However, all that is stored in the database in the fields
field is an array of strings like this: ["[object Object]"]
但是,存储在数据库中的
fields
字段中的所有内容都是一个字符串数组,如下所示: ["[object Object]"]
How can I store my Javascript array so that it matches my mongoose schema correctly? 如何存储我的Javascript数组,使其正确匹配我的猫鼬模式?
I was able to fix this using Molda's idea of using a separate schema. 我能够使用Molda的使用独立模式的想法来解决此问题。
The updated fields
field in the articleSchema
now looks like this: 现在,
articleSchema
已更新fields
字段如下所示:
fields: [{
type: Schema.Types.ObjectId,
ref: 'Field'
}]
I then converted the array to an array of schema objects, like this: 然后,我将数组转换为架构对象数组,如下所示:
keyValueObj = keyValueObj.map(function(fieldObj){
return new Field({
key: fieldObj.key,
type: fieldObj.type,
value: fieldObj.value
});
});
I was then able to store keyValueObj
the was doing it in the initial code. 然后,我能够将
keyValueObj
存储在初始代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.