首页 > 解决方案 > 将数据保存到猫鼬中的数组

问题描述

用户可以发布其他用户可以请求的项目。因此,一个用户创建一个项目,许多用户可以请求它。所以,我认为最好的方法是将一组用户放入请求它的产品模式中。现在我只想存储用户 ID 和名字。这是架构:

const Schema = mongoose.Schema;

const productSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    category: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    requests: [
        {
            userId: {type: Object},
            firstName: {type: String}

        }
    ],
});

module.exports = mongoose.model('Product', productSchema);

在我的控制器中,我首先找到该项目,然后调用 save()。

exports.postRequest = (req, res, next) => {
  const productId = req.body.productId;
  const userId = req.body.userId;
  const firstName = req.body.firstName;
  const data = {userId: userId, firstName: firstName};
  Product.findById(productId).then(product => {
    product.requests.push(data);
    return product
      .save()
      .then(() => {
        res.status(200).json({ message: "success" });
      })
      .catch(err => {
        res.status(500).json({message: 'Something went wrong'});
      });
  });
};

首先,这样可以吗?我发现了一些关于此的帖子,但他们没有找到并调用 save,他们使用 findByIdAndUpdate() 和 $push。我这样做是“错误的”吗?这是我尝试的第二种方法,我在数据库中得到了相同的结果:

exports.postRequest = (req, res, next) => {
    const productId = req.body.productId;
    const userId = req.body.userId;
    const firstName = req.body.firstName;
    const data = {userId: userId, firstName: firstName};
    Product.findByIdAndUpdate(productId, {
        $push: {requests: data}
    })
    .then(() => {
        console.log('succes');
    })
    .catch(err => {
        console.log(err);
    })
  };

其次,如果您查看屏幕截图,数据的格式和结构是否正确?我不知道为什么里面还有 _id 而不仅仅是用户 ID 和名字。在此处输入图像描述

标签: node.jsexpressmongoose

解决方案


以你的方式做这件事并没有错。在查询后使用保存使您有机会验证数据中的某些内容。并且您还可以添加其他字段(如果包含在架构中)。例如,如果您当前的 json 返回没有名为 last_name 的字段,那么您可以添加该字段并保存文档,这是一个好处..

使用 findById() 时,您实际上无权进行更改,除非您对其进行编程

我注意到的一件事..在您的架构中,使用 mongoose.modal() 编译它之后

导出已编译的模型,以便您可以在需要使用导入的任何地方使用它。像这样..

const Product = module.exports = mongoose.model('Product', productSchema);

推荐阅读