Mongoose - Как сохранить документ со встроенным документом? Пытался сделать push, не может заставить его работать

Я просмотрел https://stackoverflow.com/search?q=Mongoose+save+a+document+with+an+embedded+document и Как заполнить вложенные встроенные документы Mongoose и до сих пор не понял, что я делаю неправильно. Я хочу просто сохранить пользовательский документ со встроенной платежной информацией.

user.model.js

//Dependencies

var restful = require('node-restful');
var mongoose = restful.mongoose;

//Schemas
var paymentSchema = new mongoose.Schema({
    cardnumber: Number,
    cardtype: String
    // code: Number,
    // expiredate: Date,
    // nameoncard: String,
    // address: String,
    // state: String,
    // zip: Number
});

var userSchema = new mongoose.Schema({
    username: { type: String, required: true, index:{unique: true} }, 
    fn: String,
    email: String,
    ln: String,
    fullname: String,
    pw: { type: String, required: true}, // pwd hash
    //slt: String, //salt
    pnum: Number, //phone number
    usrtype: String,
    paymentinfo: [paymentSchema]    

});

//Return models
module.exports = restful.model('PaymentInfo', paymentSchema);
module.exports = restful.model('User', userSchema);

user.route.js

//Dependencies
var express = require('express');
var router = express.Router();
var pwdHashSalt = require('password-hash-and-salt');

var mongojs = require('mongojs');

//MongoJS-MongoDB
var db = mongojs('testDB',['users']);

//Models
var User = require('../models/users');
var PaymentInfo = require('../models/users');  

   //Routes 
router.post('/newuser', function (req, res) {
        try{

  db.users.find({username: req.body.email},function(err, docs){
            if( err || docs.length < 1){


                 console.log("user not found...ok to add");
                 var user = new User({
                         fn: req.body.fn,
                         ln: req.body.ln,
                         fullname: req.body.fullname,
                         pnum: req.body.pnum,
                         usrtype: req.body.usrtype,
                         username: req.body.email,
                         email: req.body.email//,
                         //  paymentinfo: new PaymentInfo(  req.body.paymentinfo )
                    }); 
                     var payment = new PaymentInfo(
                      { cardtype: req.body.paymentinfo.cardtype,
                        cardnumber: req.body.paymentinfo.cardnumber
                      });

                     user.paymentinfo.push(payment);



                    pwdHashSalt(req.body.password).hash(function (error, hash) {
                        if (error)
                            throw new Error('Something went wrong!');
                        user.pw = hash;
                        user.save(function(err, doc){
                        if(err){
                                console.log("error: "+err)
                            //  throw new Error("Error saving user");               
                            }
                            else{
                                res.send('success');
                            //  
                            } 
                    });                 

                    });
            }                       
            else{
                    res.send('Username taken'); 
                }
    }); 


    }
    catch(e){
        //throw new Error('Error creating new user');
        res.send('Error creating user'+e.message);
    }
    finally{

    }
});

//Return router
module.exports = router;

Тело сообщения

{
"email": "[email protected]",
"password": "hello123",
"fn": "The",
"ln": "Guy",
"fullname": "The Guy",
"pnum": 8601124485,
"usrtype": "normal",
"paymentinfo": { "cardnumber": 12312312312311, "cardtype": "Visa" }

}

Однако, когда я смотрю в базе данных, это выглядит так:

{
    "_id" : ObjectId("59d1856240250733bc79a88c"),
    "pw" : "pbkdf2$10000$27bf979ea097a1da8d3b8cd6e45ba02a62d9c3616213dc809c78c50310d66f3d6ef6a1984d2c42aea0df6b109145ebc244359b60e1096a7c0a6aef667e115205$d669bb4c703890c888842fb693fd79b1ba1140988810a1210c994c2b547d8851d8bdab3c6a0420114d2cd4cbebcc0b97a989a3a25aa6eea93034a78e03cf9ab5",
    "fn" : "The",
    "ln" : "Guy",
    "fullname" : "The Guy",
    "pnum" : 8601124485.0,
    "usrtype" : "normal",
    "username" : "[email protected]",
    "email" : "[email protected]",
    "paymentinfo" : [ 
        {
            "_id" : ObjectId("59d1856240250733bc79a88d")
        }
    ],
    "__v" : 0
}

Я не знаю, что я делаю неправильно здесь, любые предложения? Спасибо.


person JTime    schedule 02.10.2017    source источник


Ответы (1)


Я понял! Я не получал значения в публикуемом массиве.

удаление этой части:

 var payment = new PaymentInfo(
                      { cardtype: req.body.paymentinfo.cardtype,
                        cardnumber: req.body.paymentinfo.cardnumber
                      });

                     user.paymentinfo.push(payment)

И заменив его на это:

req.body.paymentinfo.forEach(function(card) {
                        user.paymentinfo.push(card);
});

Также нет необходимости экспортировать модель PaymentSchema

module.exports = restful.model('PaymentInfo', paymentSchema);
person JTime    schedule 03.10.2017