【问题标题】:How to use object id that give reference in nodejs mongodb如何使用在nodejs mongodb中提供参考的对象ID
【发布时间】:2017-05-07 01:11:48
【问题描述】:

没有其他错误,但我只想知道一件事。如何在用户模式对象 _id 中使用该引用,这意味着 location_id 在我添加新用户时如何使用。

用户架构:

    var userSchema = Mongoose.Schema({ 

        name:{type: String,require:true},
        surname: {type: String,require:true},
        tel: {type: String,require:true},
        age: {type: String,require:true},
        mevki_id: {type: String,require:true},
        location_id: { type: Mongoose.Schema.Types.ObjectId, ref: 'locations' }
});

位置架构:

var LocationSchema = Mongoose.Schema ({         


    il: {type: String, require:true},

    ilce: {type:String, require:true}          

});

UserController -- 我在这里添加用户

this.createUser = function(req, res) {

    var la=new Location({il:'istanbul',ilce:'camlica',location_id:la._id}).save(function (err) {
        if (err) return handleError(err);
    });

    var user = new User({
        name:'akif',surname:'demirezen',tel:'544525',age:'45',mevki_id:'2',

    }).save(function (err) {
        if (err) return handleError(err);
    res.send(JSON.stringify(job));
    });

}

【问题讨论】:

    标签: node.js mongodb mongoose reference schema


    【解决方案1】:

    您的代码中有几个错误。例如,require 属性应为 required

    其他问题是您正在使用对 la 的引用设置 la 的 location_id 值,当时尚未分配值。

    Mongo 会自动在所有对象上创建一个名为 _id: ObjectId 的字段。试试这个:

    this.createUser = function(req, res) {
    
      var la = new Location({
        il:'istanbul',
        ilce:'camlica',
      }).save(function (err, location) {
        if (err) return handleError(err);
    
        var user = new User({
          name:'akif',
          surname:'demirezen',
          tel:'544525',
          age:'45',
          mevki_id:'2',
          location_id: location._id
        }).save(function (err, user) {
          if (err) return handleError(err);
          // Warning: AFAIK job does not exist, should it be user?
          res.send(JSON.stringify(job));
        });
      });
    }
    

    【讨论】:

    • 我真的很想你,但我想可能是这个 res.send(JSON.stringify(user));
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2012-12-02
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2011-05-02
    相关资源
    最近更新 更多