Mongoose没有将传递的字段保存到集合中

时间:2017-01-08 20:35:25

标签: node.js mongodb express mongoose

我有一个具有以下定义的Mongoose模式:

var mongoose        = require('mongoose');
var accountSchema   = require('./accountSchema.js');   
var orders          = require('./orderSchema.js');

var schema = new mongoose.Schema({
    truckId: String,
    truckDetails: {
        licensePlate: String,
        model: String,
        make: String
    },
    driver: accountSchema.schema,
    onboard: [orders.schema]
},{
    collection: 'truckMap'
});

truckModel = mongoose.model('truckMapSchema', schema);

将文档保存到我的mongodb数据库的API路由:

router.post('/api/update/truckmap/',
function(req, res, next) { passport.authenticate('jwt',
function(err, user, info){

    if(err) { return next(err) }
    if(!user) { return res.json({ success: "false" , status: 403, msg: "Authentication failed."})}

    Account.findOne({email: user.local.email}, function(err, docs){
        if(err){ res.send({success: 'false', msg: 'Error occured while trying to find driver.'})}

        if(!docs) { res.send({sucess: 'false', msg: 'Driver not found.'})}
        else {
            var truck = new Truck();

            truck.truckId = req.body.truck_id;
            console.log('licensePlate: ' + req.body.license_plate);

            truck.truckDetails.licencePlate = req.body.license_plate;
            truck.truckDetails.model = req.body.model;
            truck.truckDetails.make = req.body.make;

//                truck.driver = driver;
            truck.onboard = [];

            truck.save();
            res.send({success: true, msg: "truckmap updated"})
        }
    });

    })(req, res, next);
});

现在,当我使用POST请求传递以下信息时:

header - 
    Authorization: <jwt token>

body - 
    email: admin@cc.com
    truck_id: 1
    license_plate: 1234a
    model: asdf
    make: qwer

它在我的集合中创建了一个文档,但是缺少truckDetails下的licensePlate字段:

{
    "_id" : ObjectId("5872a113e41d0076628ddf74"),
    "truckId" : "1",
    "onboard" : [ ],
    "truckDetails" : {
        "make" : "qewr",
        "model" : "asdf"
    },
    "__v" : 0
}

在路线功能的上方,我记录了输出正确值的req.body.license_plate的值。

我认为它可能是一个嵌入式文档问题,但modelmake存储没有任何麻烦。

不确定如何前进。

2 个答案:

答案 0 :(得分:1)

您的代码中似乎有一些小错误。

truckMap架构

truckDetails: {
    licensePlate: String, // notice the `s`
    model: String,
    make: String
},

POST请求

header - 
    Authorization: <jwt token>

body - 
    email: admin@cc.com
    truck_id: 1
    license_plate: 1234a  // `s` here too
    model: asdf
    make: qwer

虽然您是控制台记录您的值,但它具有正确的拼写

console.log('licensePlate: ' + req.body.license_plate); // `s` here too

但保存时您使用的是c而不是s

truck.truckDetails.licencePlate = req.body.license_plate;

答案 1 :(得分:0)

混合类型在没有Mongoose帮助的情况下不会进行更改跟踪。加入:

truck.markModified('truckDetails'); 
保存之前