gpt4 book ai didi

javascript - 如何将新对象添加到 Mongoose 中的数组?

转载 作者:可可西里 更新时间:2023-11-01 10:03:31 24 4
gpt4 key购买 nike

当我将新的评论文档推送到 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 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
}

最佳答案

尝试使用 findOneAndUpdate$addToSet 运算符 (http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate),而不是使用 findOne

它看起来像:

Story.findOneAndUpdate(
{_id: req.params.id},
{$addToSet: {comments: comment}},
function(err,data) {
if(err) throw err;
}
)

关于javascript - 如何将新对象添加到 Mongoose 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32059824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com