【发布时间】:2021-02-08 22:41:14
【问题描述】:
我对 mongoose 和 nodejs 还很陌生,所以我在做我的项目时参考了 mongoose 文档。我想通过使用其 id 标识子文档来删除评论数组中的特定子文档。如图所示,我尝试使用“pull”和“id”方法进行操作。我在我的语法中也找不到任何错误,但它仍然有效。
这是来自我的数据库的示例文档:
{
comments: [
{
replyComment: [],
_id: 601a673735644c83e0aa1be3,
username: 'xyz123@gmail.com',
email: 'xyz123@gmail.com',
comment: 'test123'
},
{
replyComment: [],
_id: 601a6c94d1653c618c75ceae,
username: 'xyz123@gmail.com',
email: 'xyz123@gmail.com',
comment: 'reply test'
},
{
replyComment: [],
_id: 601eb7ba7233015d7090c6bf,
username: 'xyz123@gmail.com',
email: 'xyz123@gmail.com',
comment: 'test comment'
},
{
replyComment: [],
_id: 601ec090f5f22d75b41bec7b,
username: 'xyz123@gmail.com',
email: 'xyz123@gmail.com',
comment: 'test comment123'
}
],
_id: 601a3b8038b13e70405cf9ea,
title: 'latest test',
snippet: 'latest test snippet',
body: 'latest test body',
createdAt: 2021-02-03T05:58:24.123Z,
updatedAt: 2021-02-07T06:56:53.902Z,
__v: 15
}
通过这个测试 findById("601a3b8038b13e70405cf9ea") 和 console.log(result)
我的 topicSchema 文件:
const mongoose = require('mongoose');
const Schema =mongoose.Schema;
const topicSchema = new Schema({
title: {
type: String,
required: true
},
snippet: {
type: String,
required: true
},
body: {
type: String,
required: true
},
comments: {
type: Array,
required: false
}
}, {timestamps: true},{ versionKey: false });
const Topic = mongoose.model('Topic', topicSchema);
module.exports = Topic;
我的commentSchema 文件:
const mongoose = require('mongoose');
const Schema =mongoose.Schema;
const comSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
comment: {
type: String,
required: true
},
replyComment: {
type: Array,
required: false
},
}, {timestamps: true},{versionKey: false});
const Comm = mongoose.model('comm', comSchema);
module.exports = Comm;
【问题讨论】:
标签: node.js mongodb express mongoose pull