【问题标题】:Storing a one to many relationship in Node.js using Mongoose使用 Mongoose 在 Node.js 中存储一对多关系
【发布时间】:2017-04-14 03:16:10
【问题描述】:

我有一个非常简单的一对多关系,其中User 有一个Alerts 列表。为此,我定义了以下模式:

var userSchema = new Schema({
    email: String,
    alerts: [{type: Schema.Types.ObjectId, ref: 'Alert'}]
});
var User = mongoose.model('User', userSchema);

var alertSchema = new Schema({
    _creator: {type: Schema.Types.ObjectId, ref: 'User'},
    value: String,
});
var Alert = mongoose.model('Alert', alertSchema);

现在,我正在尝试创建一个函数,该函数创建一个新的 Alert 并将其添加到数据库中的现有 User 中。我有以下代码(删除错误处理,因此代码更短):

function createAlertForUser(userId, value) {
    User.findOne({_id: userId}, function (error, user) {

        var alert = new Alert({
            _creator: userId,
            value: value
        });

        alert.save(function (error, alert) {

            // push it to the user
            user.alerts.push(alert);
            user.save(function(error) {
                console.log("saved");
            });
        });
    });
}

但是,当我检查数据库时,我似乎将空值保存到用户的警报列表中。有什么我想念的想法吗?

【问题讨论】:

  • 你确定这里使用的userId已经是ObjectId了吗?

标签: javascript node.js mongodb mongoose mongoose-populate


【解决方案1】:

您尝试将整个 Alert 对象推送到 ObjectId 数组中。

试试这个:

user.alerts.push(alert.id);

user.alerts.push(alert._id);

两者都是正确的。

【讨论】:

  • 确实推送 id 而不是对象是根本问题。
猜你喜欢
  • 2016-05-02
  • 2015-12-06
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-08-18
  • 2011-12-10
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多