【发布时间】:2015-11-09 13:39:29
【问题描述】:
我对 Mongoose 还很陌生。我的目标是能够将数据推送到 Mongoose 数组中,以便稍后循环遍历它: 这是我的架构:
var moduleSchema = new mongoose.Schema({
name: {type: String, index: {unique: true}},
priority: Number,
author: String,
enabled: Boolean,
keywords: [{keyword: String}],
code: String
});
我希望能够将这种格式的 JavaScript 对象发送到 express 并插入它自己的“关键字”字段。理想情况下,输出应如下所示:
{
"_id": "56401885bff833582442bb5f",
"name": "ModName",
"priority": 1,
"author": "tscrip",
"enabled": true,
"code": "TEST",
"__v": 0,
"keywords": [
{
"keyword": "Dog",
"keyword": "Cat"
}
]
}
每次我 PUT 数据来更新这个时,我都会得到:
0:D,
1:O,
2:G
或者我得到:
The argument to $each in $push must be an array but it was of type Object
这是我更新模型的代码:
if(req.body.keywords) updateObj.keywords = JSON.parse(req.body.keywords);
var keywordsArr = updateObj.keywords;
Module.findByIdAndUpdate({
"_id": req.params.id
},
{ $set: {keywords: { $each: { keyword: {keywordsArr}}}}},
function(err, numAffected){
console.log(err);
}
);
我正在向它发送一个简单的 JSON 对象来更新:
{
"keywords": [
"mouse",
"bird"
]
}
任何帮助将不胜感激。
更新 1
我试图把它变成一个数组:
var moduleSchema = new mongoose.Schema({
name: {type: String, index: {unique: true}},
priority: Number,
author: String,
enabled: Boolean,
keywords: [String],
code: String
});
然后像这样更新它:
if(req.body.keywords) updateObj.keywords = JSON.parse(req.body.keywords);
var keywordsArr = updateObj.keywords.keywords;
console.log(keywordsArr);
Module.findByIdAndUpdate({
"_id": req.params.id
},
{ $push: {keywords: {$each: keywordsArr}}},
function(err, numAffected){
console.log(err);
}
);
但我现在得到一个错误:
{ [MongoError: exception: The field 'keywords' must be an array but is of type Object in document {_id: ObjectId('56401885bff833582442bb5f')}]
name: 'MongoError',
message: 'exception: The field \'keywords\' must be an array but is of type Object in document {_id: ObjectId(\'56401885bff833582442bb5f\')}'
【问题讨论】:
-
将它们存储为对象有什么原因吗?
-
可能不会。无论如何,将它们存储为数组可能会更好。我尝试将我的 JSON 推送到数组中,但这不起作用。我收到错误:Cast to undefined failed for value "[object Object[" at path "keywords".
标签: javascript json node.js mongodb express