javascript - Set mongo's _id with a custom UID -
background:
i have no control on post event coming db document called things. when post comes in, i've written function called findorcreate()
.(which either find or create record(object?) in things document). reduce redundancy, want use 3rd party post payload field nuid
replace default _id
of record(object).
question:
how can replace _id payloads field called
nuid
?
example payload:
curl -h "content-type: application/json" -x post -d '{"participant":{"nuid":"98asdf988sdf89sdf89989sdf9898"}}' http://localhost:9000/api/things
schema
'use strict'; var mongoose = require('mongoose'), schema = mongoose.schema; var thingschema = new schema( {nuid: string} ); module.exports = mongoose.model('thing', thingschema);
thing.controller.js
//*currently function have both _id , nuid (which works not desirable) exports.findorcreate = function(req, res) { var query = {"nuid": req.body.participant.nuid}; var update = {nuid: req.body.participant.nuid}; thing.findoneandupdate( query, update, {upsert: true}, function(err, thing){ console.log(thing, "thing"); console.log(err, "err"); if(!thing) { thing.create(req.body.participant, function(err, thing) { if(err) { return handleerror(res, err); } }); }; if(err){return handleerror(res, err); } } ); });
thing/index.js
var express = require('express'); var controller = require('./thing.controller'); var router = express.router(); router.get('/', controller.index); router.get('/:id', controller.show); router.post('/', controller.findorcreate); router.put('/:id', controller.update); router.patch('/:id', controller.update); router.delete('/:id', controller.destroy); module.exports = router;
i found reference still don't understand on how use given model happens before payload stack reference
you can set value of _id
whatever want here , "upsert" well. it's matter of using $setoninsert
in update statement:
var thingschema = new schema({ "_id": string },{ "_id": false }); var thing = mongoose.model('thing',thingschema); thing.findbyidandupdate("98asdf988sdf89sdf89989sdf9898", { "$setoninsert": { "_id": "98asdf988sdf89sdf89989sdf9898" } }, { "upsert": true }, function(err,doc) { if (err) throw err; console.log(doc); } )
and creates new document if _id
not exist or applies update ( in example nothing updated, matched , returned ) document matched.
if have other data want update use $set
or other operators fields want alter other _id
.
as alternate generating uuid client api ( or safety ) use node-uuid
, plug generation schema:
var thingschema = new schema({ "_id": { "type": string, default: function genuuid() { uuid.v1() } } },{ "_id": false }); var thing = mongoose.model('thing',thingschema); thing.findoneandupdate( { "uname": "sam" }, { "$set": { "uname": "sam" } }, { "upsert": true }, function(err,doc) { if (err) throw err; console.log(doc); } )
in way when _id
not supplied operation created. trivial example here, makes point of setting default.
Comments
Post a Comment