【问题标题】:How to inserting a document with field referencing document in another collection如何在另一个集合中插入具有字段引用文档的文档
【发布时间】:2014-08-16 19:53:36
【问题描述】:

我目前正在尝试为带有文档引用的架构创建 .post 函数。但是,我不确定如何从另一个集合中检索文档引用的 ObjectID。

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);

用户.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'});
    });
});

为了创建版块,我在请求中包含版块名称和用户名。使用用户名,我执行 User.find 来查找特定用户并将其分配给 board.userid。但是,这似乎不起作用,因为 board.userid 没有出现。

任何帮助将不胜感激!

谢谢!

编辑

对所需内容的更好解释是我有一个现有的用户集合。当我想向 Board 中添加一个新文档时,我会提供一个用户名,从中搜索 User 集合,获取特定用户的 ObjectId 并将其作为 userid 添加到 Board 文档中。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    相信你在找population

    MongoDB 中没有连接,但有时我们仍然需要引用 到其他集合中的文档。这就是人口的来源。

    试试这样的:

    //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>"
       })
    

    抱歉,我之前解决了一个不同的问题。您可能希望在某个时候使用我提供的之前的解决方案,所以我将离开它。

    回调

    用户 ID 不在板文档中的原因是因为 User.find 是异步的,并且在调用 board.save(...) 时未分配。

    这应该可以解决问题:

    (另外,我在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'});
            });
        });   
    });
    

    【讨论】:

    • 在这种情况下我如何实际使用人口?我需要的是找到从 User 集合中提供的用户名的 objectId。我不太确定如何使用人口来实现这一目标?谢谢!
    • 非常感谢!你的解决方案成功了。我尝试过使用 populate 方法,它也可以工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2016-02-22
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多