如何在猫鼬模式ID中设置特定值?

时间:2019-06-16 14:09:06

标签: javascript node.js mongoose-schema

我需要将特定值传递给猫鼬模式的id属性,以便我可以关联集合。

我尝试传递_id:false,所以猫鼬不会自动创建具有某些随机值的id字段。

我写了这个模式:

const mongoose = require('mongoose');

const DetailsSchema = new mongoose.Schema({
  _id: String,
  name: String,
  value: Number
}, {_id: false});

const Details = mongoose.model('details', DetailsSchema);

module.exports = Details;

这是我获取具体值的途径:

router.post('/api/newSolicitation', async (req, res) => {
const { value, id, name } = req.body;
const checkforid = await Details.findOne({id});

if(checkforid) {
  const result = await Details.save();
  console.log('Detail updated: ', result);

  res.json({
    success: true,
    message: 'Detail Updated'
  });
}
else {
    const detail = new Details({
        id,
        name,
        value
    });

    const submit = await detail.save();
    console.log('New detail created:', submit);

    res.json({
      success: true,
      message: 'New detail created!'
    });
   }  
});

我收到此错误消息:

UnhandledPromiseRejectionWarning: MongooseError: document must have an _id before saving

我不理解,因为我已经声明了_id及其值。

1 个答案:

答案 0 :(得分:0)

您正在尝试通过id而不是_id进行搜索和创建。

必须为文档提供_id或让MongoDB为您生成一个文档。

删除{ _id: false }并在插入时提供_id,如果没有_id,则无法创建文档,因为复制需要_id

router.post('/api/newSolicitation', async (req, res) => {
  // destucture id from req.body and rename it to _id 
  // { property: newPropertyName }
  const { id: _id, name, value } = req.body;
  const checkforid = await Details.findById(_id);

  if(checkforid) {
    const result = await Details.save();
    console.log('Detail updated: ', result);

    return res.json({
      success: true,
      message: 'Detail Updated'
    });
  }
  const detail = new Details({ _id, name, value }).save();
  console.log('New detail created:', detail);

  res.json({
    success: true,
    message: 'New detail created!'
  });
});