gpt4 book ai didi

node.js - 如何使用mongoose插入嵌套文档帖子有很多评论,评论有很多回复

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:43 24 4
gpt4 key购买 nike

我的帖子文档具有以下结构:

{
"_id" : ObjectId("5d9df11b0e0a6e032bf3117f"),
"body" : "Sample content post.",
"date" : ISODate("2019-10-07T11:02:40.126Z"),
"comments" : [
{
"comment" : "comment on post",
"_id" : ObjectId("5d9df46e0e0a6e032bf31182"),
"replies" : [
{
"reply" : "reply to comment ",
"_id" : ObjectId("5d9bec26301798056bb07ab5")
},
]
},
],

}

我想为此请求数据的特定帖子评论添加新的回复{data: req.body}

{
"data": {
"id_post": "5d9df11b0e0a6e032bf3117f",
"id_comment": "5d9df46e0e0a6e032bf31182",
"new_reply": "Another new reply to comment"
}
}

我正在使用nodejs/express/mongoose,你能指导我如何添加新回复吗?

   router.post("/saveReply", function(req, res, next){
const query = Post.findById(req.body.id_post);
const updatePost = async () => {
try {
await Post.updateOne(
{
"_id": req.body.id_post,
"comments._id": req.body.id_comment
},
{
"$push": {
"comments.$.replies": {
"reply": req.body.reply,
}
}
},
);
}
catch (error) {
console.log('💥', error);
}
};

updatePost().then(() => console.log('✅Post updated successfully!'));

});

最佳答案

您可以使用更新操作和位置$运算符来完成此用例。

示例:

app.js 添加 mongoose 连接

const mongoose = require('mongoose');

const dbURI = 'mongodb://localhost:27017/post'

mongoose.Promise = global.Promise;

mongoose.connection.openUri(config.dbURI);

mongoose.connection.on('connecting', () => {
console.log('connecting to MongoDB...');
});

mongoose.connection.on('connected', () => {
console.log('Mongoose default connection open to ' + config.dbURI);
});

mongoose.connection.on('error', (err) => {
console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', () => {
console.log('Mongoose default connection disconnected');
mongoose.connect(dbURI, {server: {auto_reconnect: true}});
});

post.js模型文件

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

let postSchema = new Schema({
body: String,
date:Date,
comments : Array
}
);


let postCollection = mongoose.model('posts', postSchema);

module.exports = postCollection;

API

let post = require('post-model-file');


let addReply = async ()=>{

try{
await post.update(
{
"_id" : ObjectId("5d9df11b0e0a6e032bf3117f"),
"comments._id" :ObjectId("5d9df46e0e0a6e032bf31182")
},
{
"$addToSet" : {
"comments.$.replies" : {
"reply" : "reply to comment ",
"_id" : ObjectId("5d9bec26301798056bb07ac5")
}
}
}
);
}
catch(e){

console.error(e)
}
}

欲了解更多信息,请查看https://docs.mongodb.com/manual/reference/operator/update/positional/

关于node.js - 如何使用mongoose插入嵌套文档帖子有很多评论,评论有很多回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317902/

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