【问题标题】:how to work with 2 schemas, how to save correctly Mongoose, nodejs, express如何使用 2 个模式,如何正确保存 Mongoose、nodejs、express
【发布时间】:2016-03-19 15:54:31
【问题描述】:

Hej 那里,我正在尝试保存到 2 个模式并返回结果,我认为问题是保存,我得到了我需要填充以检索数据的部分,但不是关于如何保存到它 太好了,如果有人能指出我如何保存到彼此“符号链接”的不同模式中的方向

//userlist.js

var mongoose     = require('mongoose'),
Schema       = mongoose.Schema,
DataSchema   = require('../models/data');

var UserSchema = new Schema({
  fullname: String,
  username: { type: String, unique: true },
  password: { type: String },
  admin: Boolean,
  location: String,
  email: String,
  meta: [{
    age: Number,
    gender: String
  }],
  dataSchema: [DataSchema],   /// this i dont know if it works or not
  data: {
      type: Schema.Types.ObjectId,
      ref: 'Data'
  },
  created_at: Date,
  updated_at: Date
});
module.exports = mongoose.model('Userlist', UserSchema);

//data.js

var mongoose     = require('mongoose'),
Schema       = mongoose.Schema;

var DataSchema = new Schema({
    favoritter: String,
    website: String,
    homemade: String,
    image: String,
    user: {
        type: Schema.Types.ObjectId,
        ref: 'Userlist'
    }
});



module.exports = mongoose.model('Data', DataSchema);

// userRoutes.js

exports.addUserAPI = function(req, res) {

          var user = new Userlist();
          user.fullname = req.body.fullname,
          user.username = req.body.username,
          user.admin = req.body.admin,
          user.location = req.body.location,
          user.password = req.body.password,
          user.email = req.body.email,
          user.age = req.body.age,
          user.favoritter = req.body.favoritter,
          user.website = req.body.website,
          user.image = req.body.image,
          user.homemade = req.body.homemade;
          user.save(function(err, users) {
              if (err)
              res.send(err)
              Userlist.populate(users, {path: 'data'}, function(err, data){
                return res.send(data);

              });
});

};

exports.findAllAPI = function(req, res) {
            Userlist.find({})
            .populate({ path: 'meta' })
            .populate({ path: 'data'})
            .exec(function(err, users) {
              if (err)
              res.send(err);
              console.log(JSON.stringify(users, null, "\t"))
          res.json(users);
      });
    };


 {

//控制台

"_id": "56ea6df2419e900ac9d2e4fc",
"created_at": "2016-03-17T08:42:26.837Z",
"updated_at": "2016-03-17T08:42:26.837Z",
"password": "$2a$1",
"email": "kenny@blah.dk",
"admin": true,
"username": "blahblah",
"fullname": "Kenny",
"datalist": [],
"__v": 0,
"dataSchema": [],
"meta": []

}

如您所见,在 datalist noir dataSchema 中没有任何视觉效果,也没有任何元数据...当我尝试通过控制台直接从 Data 检索时,那里什么也没有。只有在用户列表中我有一些用户。

这就是我想要的样子

    "_id": "56ea6df2419e900ac9d2e4fc",
"created_at": "2016-03-17T08:42:26.837Z",
"updated_at": "2016-03-17T08:42:26.837Z",
"password": "$2a$1",
"email": "kenny@blah.dk",
"admin": true,
"username": "blahblah",
"fullname": "Kenny",
"datalist": [
"_id": "56ea6df2419e900ac9d2e"
],
"__v": 0,
"dataSchema": [
"favoritter": "www"
"homemade": "yes"
"website": "http://"
"image": "/file/asd.jpeg"
],
"meta": [
"age": "32"
"location": "Finland"
]

}

【问题讨论】:

  • 我也尝试让它对 REST 友好,但对此还是很陌生 :)
  • 您遇到的具体错误/问题是什么?
  • 没有“数据”被保存到数据中,只有在用户列表中我有我在邮递员中写的“帖子”更新了我的问题
  • 您能否举例说明您希望文档的外观?
  • @JuanCarlosFarah 更新了我希望它看起来如何的示例,如果可能的话

标签: javascript node.js mongodb express mongoose


【解决方案1】:

我创建了两个模式,第一个是 person,第二个是包含对 person 的引用的地址。希望这对您有所帮助。

架构一

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var personSchema = new Schema({
    name: String
},{collection:'person'});
module.exports = mongoose.model('person',personSchema);

模式二

var mongoose = require('mongoose');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var addressSchema = new Schema({
    address:String,
    postalCode:Number,
    personid : {type:ObjectId, ref:'person'}
},{collection:'address'});

module.exports = mongoose.model('address',addressSchema);

保存时

// Schema obj
var personSchema = mongoose.model('person',person.personSchema);
var addressSchema = mongoose.model('address',address.addressSchema);

var newPerson = new personSchema({name:'yourname'});
newPerson.save();
var newAddress = new addressSchema({address:'yourAddress',postalCode:666,personid:newPerson._id});
newAddress.save();

获取时

addressSchema.find().populate('personid').exec(function (err,res) {
        if(err){
            console.log('error');
        }
        else{
            console.log(res);
            // or just name
            console.log(res.personid.name);
        }
    });

【讨论】:

  • 现在保存部分工作了,谢谢,但是,提取不起作用,即使我填充用户列表,我也无法获得全名..
  • 在您的情况下,它将是用户而不是用户列表
  • console.log(JSON.stringify(data.user.fullname, null, "\t")) ^ TypeError: Cannot read property 'fullname' of undefined
  • 用户在填充或 console.log(res.userlist.fullname) 中?
  • schemaName.find().populate('user').exec(function (err,res) { if(err){ console.log('error'); } else{ console.log (res.user.fullname); } });
猜你喜欢
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2011-06-28
  • 2016-01-02
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多