如何按子文档和文档查找,更新正在推送子文档



所以我有这个模型

const postSchema = new mongoose.Schema({
image: [{type: String, required: true, unique: true}],
comments: [{
id: {type: mongoose.Schema.Types.ObjectId},
user: {type: mongoose.Schema.Types.ObjectId, ref: 'user'},
comments: {type: String},
like: [{type: mongoose.Schema.Types.ObjectId, ref: 'user'}],
time: {type: Date, default: Date.now}
}],
caption: {type: String},
user: {type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true},
like: [{type: mongoose.Schema.Types.ObjectId, ref: 'user'}],
status: {type: Number,default: 0}
}, {timestamps: true});

我正在尝试做的是根据评论的ID推送评论 我试过了

Post.findOneAndUpdate({
_id:req.body.postid,
'comments.id':req.body.id
}, {
$push :{
"comments.$.like" : res.userdata.id
}
}, {}, err => {
if(err){
res.status(500).json({
err: err
})
}else {
res.status(200).json({
message: "success",
});
}
});

但它不起作用..更糟糕的是,当我找到帖子时,这是文档

"_id" : ObjectId("5d6d4754599d8b06c01b1894"),
"image" : [
"2019-09-02T16-46-11.835Z123 - Copy.jpg",
"2019-09-02T16-46-11.892Z123.jpg",
"2019-09-02T16-46-11.938Z8358-dragon-1680x1050-digital-art-wallpaper - Copy.jpg",
"2019-09-02T16-46-11.943Z8358-dragon-1680x1050-digital-art-wallpaper.jpg",
"2019-09-02T16-46-11.949Zasd.jpg",
"2019-09-02T16-46-11.979Zasd1.jpg",
"2019-09-02T16-46-11.991Zwallpaper2you_567134.jpg"
],
"like" : [ ],
"status" : 0,
"caption" : "asd",
"user" : ObjectId("5d6c8d934a401d3748ef0c3e"),
"comments" : [
{
"like" : [ ],
"_id" : ObjectId("5d6d476f599d8b06c01b189a"),
"time" : ISODate("2019-09-02T16:46:39.499Z")
}
],
"createdAt" : ISODate("2019-09-02T16:46:12.034Z"),
"updatedAt" : ISODate("2019-09-02T16:46:39.498Z"),
"__v" : 0

idk 为什么用户和评论子文档被删除,甚至喜欢字段也不会推送

注意:我的猫鼬依赖"mongoose": "^5.6.4",

有什么建议吗? 对不起,我的英语不好

你可以通过以下方法使用 ,

Post.findOne({_id:req.body.postid,
'comments.id':req.body.id })
.exec((err , foundObject)=>{
if(err){
console.log(err);
}else{
console.log("Object ===>" . object);
object.comments.push( res.userdata.id);
object.save(function (err) {
if(err) {
console.error('ERROR!');
}
}); 
}
});

你确定req.body.postidres.userdata.idreq.body.id的类型是 ObjectId 吗?试试这种方式

Post.findOneAndUpdate(
{
_id: ObjectId(req.body.postid),
comments.id: ObjectId(req.body.id)
}, 
{
$push: {
comments.like: ObjectId(res.userdata.id)
}
}, {}, err => {
if (err) {
res.status(500).json({
err: err
})
} else {
res.status(200).json({
message: "success",
});
}
}
);

最新更新