mongoose 从Angular 将数据推送到Mongo文档

gj3fmq9x  于 2023-02-19  发布在  Go
关注(0)|答案(1)|浏览(68)

我有一个模式的数据,我想把它推到一个不同模式的文档中。我想把一个对象推到一个有数组值的Mongo文档中。
在一个Angular 组件中,我有一个函数来验证一个形式:

public validate(): void {
    ....
    this._httpService.postFormResults(this.user);
  }

在HttpService中:

postFormResults(formData: IUser) {
    return this._http
      .post<IUser>("/my-route", formData)
      .subscribe((responseData) => {
        console.log(responseData);
      });
  }

这是我的界面:

export class IUser {
  caption: string;
  email: string;
  firstname: string;
  lastname: string;
  city: string;
  state: string;
  country: string;
}

其次是快速路线:
app.use('/my-route', require('./route..'));
路线为:

router.post('/', function (req, res, next) {
  const formData = new CaptionData({
    caption: req.body.caption,
    email: req.body.email,
    firstname: req.body.firstname,
    lastName: req.body.lastname,
    city: req.body.city,
    state: req.body.state
  })
  formData.save();
  res.status(201).json({
    message: 'Form submission added successfully'
  });
});

module.exports = router;

这是一个模型:

const mongoose = require('mongoose');
const userData = mongoose.Schema({
    caption: { type: String, required: true },
    email: { type: String, required: true },
    firstname: { type: String, required: true },
    lastname: { type: String },
    city: { type: String },
    state: { type: String }
});

module.exports = mongoose.model('Post', userData);

上面的一切都在工作。我的问题是,我如何将上面的数据推送到一个完全不同的结构?我在哪里引用文档ID?我想将上面的数据(一个对象)推送到下面所示的标题。我如何引用现有的Mongo文档ID并推送到新的数据?

export class UserDataInterface {
  imageURL: string;
  altText: string;
  totalCaptions: number;
  captions: [{userData}, {userData}, {userData}]
  cached: boolean;
  itemIndex: number;
}

我找到了2018年的this post,这是一个可行的解决方案吗?
formData.update( { _id: how to get the ID?}, { $push: {"captions": userData}})
This one也是类似的,但我不是很清楚。

vmdwslir

vmdwslir1#

您应该在另一个模式中将captions属性声明为ref数组:

const otherSchema = new mongoose.Schema({
    captions: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }]
});

然后,您可以将新CaptionData的引用$pushotherSchema中(假设您将模型导入为Other):

router.post('/', async function (req, res, next) {
    const formData = await CaptionData.create({
      caption: req.body.caption,
      email: req.body.email,
      firstname: req.body.firstname,
      lastName: req.body.lastname,
      city: req.body.city,
      state: req.body.state
    })
    await Other.findByIdAndUpdate(<id-of-other>, { $push: { captions: formData._id }});
    res.status(201).json({
      message: 'Form submission added successfully'
    });
  });
  
  module.exports = router;

最后,要在查询otherSchema时检索标题的值,可以使用以下内容填充它们:

Other.find({}).populate('captions').exec();

相关问题