BleachedAxe
BleachedAxe

Reputation: 403

MongoDB - Concatenating two properties in a model and updating the model with the result

I am trying to concatenate two things in this model.

router.post('/', (req, res) => {
let file= new File({
    name: req.body.name,
    year: req.body.year,
    code: req.body.code
});
file.save().then(data => {
    res.send(data);
}, err => {
    res.send(err);
})});

So what I want to do is that I want to take the input from the user for name and year, and once the post request goes through I want to take name+'_'+ Last six characters of MongoDB object ID and update the model and patch code with the result. How am I able to achieve this in an efficient way? Any help would be appreciated. Thanks!

Sample doc

{ "_id": { "$oid": "5aa420c2f92b4d77fc342e62" }, "name": "n", "year": "1992", "code": "", "__v": 0 }

Sample output for the field "code" from above document.

"code": "n_342e62"

The code should update after the post request by itself by concatenating those two properties.

Upvotes: 2

Views: 184

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 10111

try this, Generate mongo Id before saving data.

const mongoose = require('mongoose');
router.post('/', async (req, res) => {
  try {
    const body = req.body;
    let id = mongoose.Types.ObjectId();
    body._id = id;
    id = id.toString();
    let file = new File();
    data.code = `${data.name}_${id.substr(id.length - 6)}`;
    file = Object.assign(file, body);
    const data = await file.save();
    res.json(data);
  } catch (error) {
    res.send('Something went wrong');
  }
});

Upvotes: 0

Shimon Brandsdorfer
Shimon Brandsdorfer

Reputation: 1723

I don't understand why you would want to do it only after the post request has been finished. But here is how you can do it:

router.post('/', (req, res) => {
let file= new File({
    name: req.body.name,
    year: req.body.year,
    code: req.body.code
});
file.save().then(data => {
    res.send(data);

    //after the DATA has been sent, you can save the code
    let id = data._id.toString();
    data.code = data.name + "_" + id.slice(id.length - 6, id.length);
    data.save();
}, err => {
    res.send(err);
})});

(Also, Please clarify whether you want to take the name or the year for the code).

Upvotes: 1

Related Questions