简体   繁体   中英

How to inserting a document with field referencing document in another collection

I am currently attempting to create a .post function for a schema with document reference. However, I am not sure how I can retrieve the ObjectID of the document reference from another 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 the board, I include a boardname and a username in my request. Using the username, I do a User.find to find the specific user and assign it to board.userid. However, this does not seem to be working as board.userid does not appear.

Any help would be greatly appreciated!

Thank you!

EDIT

A better explanation of what is required is that I have an existing User collection. When I want to add a new document to Board, I would provide a username, from which I would search the User collection, obtain the ObjectId of the specific user and add it as userid to the Board document.

I believe you are looking for population

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.

Try something like this:

 
 
 
  
  //small change to 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 is %s', board.user._id); // prints "The user id is <some id>" })
 
  

Sorry, I solved a different problem previously. You'll probably want to use the prevoius solution I provided at some point, so I'm leaving it.

Callbacks

The reason the userid is not on the board document is because User.find is asynchronous and is not assigned at the moment board.save(...) is called.

This should do the trick:

(Also, I added a couple of returns to 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 the return here! board.userid = user._id; board.save(function(err) { if(err) return res.send(err); //<-- note the return here! res.json({message: 'New Board 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