Mongoose - 获取和删除子记录

问题描述

我有一个这样定义的模型:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const FeedbackSchema = new Schema({
  Name: {
    type: String,required: true,},Email: {
    type: String,Project: {
    type: String,Wonder: {
    type: String,Share: {
    type: String,Delight: {
    type: String,Suggestions: {
    type: String,rating: {
    type: String,dateCreated: {
    type: Date,default: Date.Now(),user: {
    type: Schema.Types.ObjectId,ref: 'User'
  }

});

const UserSchema = new Schema({
  googleId: {
    type: String
  },displayName: {
    type: String
  },firstName: {
    type: String
  },lastName: {
    type: String
  },image: {
    type: String
  },createdAt: {
    type: Date,Feedback: [FeedbackSchema],})

module.exports = mongoose.model("User",UserSchema);

示例文档:

{
    _id: ObjectId('60b9dc728a516a4669b40dbc'),createdAt: ISODate('2021-06-04T07:42:01.992Z'),googleId: '2342987239823908423492837',displayName: 'User Name',firstName: 'User',lastName: 'Name',image: 'https://lh3.googleusercontent.com/a-/89wf323wefiuhh3f9hwerfiu23f29h34f',Feedback: [
        {
            dateCreated: ISODate('2021-06-04T07:42:01.988Z'),_id: ObjectId('60b9dc858a516a4669b40dbd'),Name: 'Joe Bloggs',Email: 'joe@bloggs.com',Project: 'Some Project',Suggestions: 'Here are some suggestions',rating: '10'
        },{
            dateCreated: ISODate('2021-06-04T08:06:44.625Z'),_id: ObjectId('60b9df29641ab05db7aa2264'),Name: 'Mr Bungle',Email: 'mr@bungle',Project: 'The Bungle Project',Suggestions: 'Wharghable',rating: '8'
        },{
            dateCreated: ISODate('2021-06-04T08:08:30.958Z'),_id: ObjectId('60b9df917e85eb6066049eed'),Name: 'Mike Patton',Email: 'mike@patton.com',Project: 'No More Faith',Suggestions: 'Find the faith',],__v: 0
}

我定义了两条路由,第一个用户单击 UI 上反馈项上的按钮时调用,该按钮将用户带到“您确定要删除此记录吗”类型的页面显示一些来自所选反馈记录的信息。

第二条路径,当用户点击“确认”时,子记录将从文档中删除

我遇到的问题是我似乎无法从用户那里获取反馈以通过 id 选择文档,这是我迄今为止的确认路线:

router.get('/delete',ensureAuth,async (req,res) => {
    try {
        var url = require('url');
        var url_parts = url.parse(req.url,true);
        var FeedbackId = url_parts.query.id;

        const allFeedback = await User.Feedback;
        const FeedbackToDelete = await allFeedback.find({ _id: FeedbackId });

        console.log(FeedbackToDelete);

        res.render('delete',{
            imgSrc: user.image,displayName: user.firstName,FeedbackToDelete
        });
    } catch (error) {
        console.log(error);
    }
})

非常感谢帮助

解决方法

更新

你应该能够做到这一点:

const feedbackToDelete = await User.feedback.find({ _id: feedbackId });

或者,如果 feedbackId 只是一个字符串,看起来是这样,您可能需要执行以下操作:

// Create an actual _id object
// That is why in your sample doc you see ObjectId('foobarbaz')
const feedbackId = new mongoose.Types.ObjectId(url_parts.query.id);
const feedbackToDelete = await User.feedback.find({ _id: feedbackId });

原创

不应该这样:

const allFeedback = await User.feedback;(一个字段)

就这样:

const allFeedback = await User.feedback();(方法/函数)