用猫鼬将数据保存到数组

时间:2019-01-11 09:34:44

标签: node.js express mongoose

用户可以发布其他用户可以请求的项目。因此,用户创建一个项目,许多用户可以请求它。因此,我认为最好的方法是将一组用户放入请求谁的产品架构中。现在,我只想存储该用户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和名字。 enter image description here

2 个答案:

答案 0 :(得分:1)

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

使用findById()时,除了编程要执行的操作之外,您实际上无权进行更改

我注意到的一件事。在您的模式中,使用mongoose.modal()编译后

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

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

答案 1 :(得分:1)

通常,开发人员将仅在集合(产品)中保存其他集合(用户)的引用。此外,您还保存了用户名。很好。

您的两种方法均有效。但是,正是为了您的特定需求,MongoDB中添加了第二种方法。因此,使用第二种方法没有危害。

相关问题