简体   繁体   中英

How to set an specific value in mongoose Schema id?

I need to pass a specific value to the id propertie of the mongoose Schema so i can relate collections.

I've tried passing the _id: false so mongoose wouldn't create the id field automaticaly with some random value.

I wrote this schema:

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;

This is my route to receive the specific value:

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!'
    });
   }  
});

I have this error message:

UnhandledPromiseRejectionWarning: MongooseError: document must have an _id before saving

Which i don't understand because i already declared the _id and it's value.

You are trying to search and create by id instead of _id .

You have to provide _id to a document or let MongoDB generate one for you.

Remove { _id: false } and provide _id on insert, Its impossible to create a document without _id because _id is required for replication.

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!'
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM