Javascript 如何在Mongoose中向数组添加新对象?
在Mongoose中将新的评论文档推送到故事集中时,我不断遇到以下错误:Javascript 如何在Mongoose中向数组添加新对象?,javascript,node.js,mongodb,mongoose,nosql,Javascript,Node.js,Mongodb,Mongoose,Nosql,在Mongoose中将新的评论文档推送到故事集中时,我不断遇到以下错误: { [MongoError: The field 'comments' must be an array but is of type Object in document {_id: ObjectId('55d2429477da83b6f593ce53')}] name: 'MongoError', message: 'The field \'comments\' must be an array but is
{
[MongoError: The field 'comments' must be an array but is of type Object in document {_id: ObjectId('55d2429477da83b6f593ce53')}]
name: 'MongoError',
message: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}',
driver: true,
index: 0,
code: 16837,
errmsg: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}'
}
这是我的模型:
var commentSchema = new Schema({
text: String,
date: { type: Date, default: Date.now },
author: String
})
var storySchema = new Schema({
title: String,
link: String,
comments: [commentSchema],
author: String,
date: { type: Date, default: Date.now }
});
这是我的疑问:
app.post('/news/:id/comment', function(req, res) {
console.log('Hi Received');
var comment = {
"author": 'Steven',
"text": req.body.comment
}
Story.findOne({_id: req.params.id}, function(err, data) {
if(err) throw err;
data.comments.push(comment);
data.save(function(err, data){
if (err) console.log(err);
console.log(data);
});
})
});
我试着用谷歌搜索解决方案,但仍然无法修复错误
编辑:
我当前要添加到的集合如下所示:
> db.stories.find().pretty()
{
"_id" : ObjectId("55d2429477da83b6f593ce53"),
"author" : "Steven Chen",
"link" : "AS",
"title" : "AS",
"date" : ISODate("2015-08-17T20:22:44.271Z"),
"comments" : {
"author" : "Steven",
"text" : "Alsawdksada"
},
"__v" : 0
}
不要使用
findOne
,而是尝试使用findOneAndUpdate
和$addToSet
操作符()
它看起来像:
Story.findOneAndUpdate(
{_id: req.params.id},
{$addToSet: {comments: comment}},
function(err,data) {
if(err) throw err;
}
)
您应该在“注释”字段中插入错误的第一个条目。 由于这是一个数组,您必须在注释数组中推送对象。在插入第一条注释时,您似乎直接将注释对象分配到“注释”字段。
请检查相同的字段,它将被重新解决尝试,但仍然返回相同的类似错误:
MongoError:exception:无法将$addToSet应用于非数组字段。名为“comments”的字段在文档中有一个非数组类型的对象_id:ObjectId('55d2429477da83b6f593ce53')
更新后-您的注释架构看起来像是单个对象而不是列表。请尝试在{“author”:“Steven”,“text”:“Alsawdksada”}周围添加另一组大括号
我更新了MongoI中当前集合的外观,我想我知道问题所在。这可能与我最初插入数据的方式有关。我就是这样做的:for(var x=0;x
yep!尝试从空注释开始,然后使用post方法,一切都会好起来。您的收集文档与您的架构不匹配。正如错误消息所述,comments
是一个对象,而不是数组。