Node.js 如何在mongodb的嵌套数组中插入数据?
这是我的post模型,它存储在mongodb中Node.js 如何在mongodb的嵌套数组中插入数据?,node.js,mongodb,express,mongoose,nosql,Node.js,Mongodb,Express,Mongoose,Nosql,这是我的post模型,它存储在mongodb中 const PostSchema = new mongoose.Schema({ text: { type: String, required: "Name is required", }, photo: { data: Buffer, contentType: String, }, likes: [{ type: mongoose.Schema.ObjectId, ref:
const PostSchema = new mongoose.Schema({
text: {
type: String,
required: "Name is required",
},
photo: {
data: Buffer,
contentType: String,
},
likes: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
comments: [
{
text: String,
created: { type: Date, default: Date.now },
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
likes: Number,
incomments:[{text:String,postedBy:{ type: mongoose.Schema.ObjectId, ref: "User" }}]
},
],
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
我想在注释数组中插入注释,即在注释数组中的非注释数组中插入注释
const commentincomment=(req,res)=>{
Post.findOneAndUpdate(
{"_id":req.body.postId,
"comments.text":req.body.comment,
"comments.postedBy":req.body.postedBy
},
{$push:{"comments.$.incomments":{
text:req.body.comtext,
postedBy:req.body.userId
}}}).exec((err, result) => {
if (err) {
return res.status(400).json({
error: err,
});
}
res.json(result);
});
}
我正在执行此操作,但阵列未更新。有什么建议吗?您需要将包含字符串值的变量
posted
和postedBy
类型转换为ObjectId。
试试这个:
const mongoose=require('mongoose');
const commentincomment=(请求、回复)=>{
让条件={
“_id”:mongoose.Types.ObjectId(请求主体.postId),
“comments.text”:req.body.comment,
“comments.postedBy”:mongoose.Types.ObjectId(req.body.postedBy)
};
让博士后={
$push:{
“注释.$.不可注释”:{
文本:req.body.com文本,
postedBy:req.body.userId//如果需要,也可以进行类型转换。
}
}
}
让选项={
新:真的
};
邮递
.findOneAndUpdate(条件、博士后、选项)
.exec((错误,结果)=>{
如果(错误){
返回res.status(400).json({
错误:呃,
});
}
res.json(结果);
});
}
Result对象在更新之前返回文档,您是否尝试将选项作为{new:true}
传递以获取更新的对象?仍然不起作用。