javascript - How to inserting a document with field referencing document in another collection -
i attempting create .post function schema document reference. however, not sure how can retrieve objectid of document reference collection.
board.js
var mongoose = require('mongoose'); var schema = mongoose.schema; var boardschema = new schema({ boardname: string, userid: {type: schema.objectid, ref: 'userschema'} }); module.exports = mongoose.model('board', boardschema);
user.js
var mongoose = require('mongoose'); var schema = mongoose.schema; var userschema = new schema({ username: string }); module.exports = mongoose.model('user', userschema);
routes.js
router.route('/boards') .get(function(req, res) { board.find(function(err, boards) { if(err) res.send(err); res.json(boards); }); }) .post(function(req, res) { var board = new board(); board.boardname = req.body.boardname; user.find({username: req.body.username}, function(err, user) { if(err) res.send(err); board.userid = user._id; }); board.save(function(err) { if(err) res.send(err); res.json({message: 'new board created'}); }); });
to create board, include boardname , username in request. using username, user.find find specific user , assign board.userid. however, not seem working board.userid not appear.
any appreciated!
thank you!
edit
a better explanation of required have existing user collection. when want add new document board, provide username, search user collection, obtain objectid of specific user , add userid board document.
believe looking population
there no joins in mongodb still want references documents in other collections. population comes in.
try this:
//small change board schema var boardschema = new schema({ boardname: string, user: {type: schema.objectid, ref: 'user'} }); //using populate board.findone({ boardname: "someboardname" }) .populate('user') // <-- .exec(function (err, board) { if (err) .. console.log('the user %s', board.user._id); // prints "the user id <some id>" })
sorry, solved different problem previously. you'll want use prevoius solution provided @ point, i'm leaving it.
callbacks
the reason userid not on board document because user.find
asynchronous , not assigned @ moment board.save(...)
called.
this should trick:
(also, added couple of returns prevent execution after res.send(...)
)
.post(function(req, res) { var board = new board(); board.boardname = req.body.boardname; user.find({username: req.body.username}, function(err, user) { if(err) return res.send(err); //<-- note return here! board.userid = user._id; board.save(function(err) { if(err) return res.send(err); //<-- note return here! res.json({message: 'new board created'}); }); }); });
Comments
Post a Comment