mongoose CastError:对于值" [object Object]"转换为未定义失败在路径" apps"

时间:2015-11-20 13:42:02

标签: node.js mongodb express mongoose

我有一个用mongoose定义的嵌套模式:

//application.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Category = require('./category.js');

var Application = new Schema({
    title : String,
    cats : [Category]
});

Application.virtual('app_id').get(function() {
    return this._id;
});

module.exports = mongoose.model('Application', Application);

//account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Application = require('./application.js');

var Account = new Schema({
    username: String,
    password: String,
    apps: [Application]
});

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('Account', Account);

现在,如果我尝试按apps推送account这样的数组:

app.post('/application', function(req,res){
  var name = req.user.username;
  var newApp = new Application();
  newApp.title = req.body.title;
  console.log(newApp);

  Account.findOneAndUpdate({username : name},
    {$push: {apps: newApp}},
    {safe: true, upsert: true},
    function(err, model){
      if (err){
        console.log(model);
        console.error("ERROR: ", err);
        res.status(500).send(err);
     }else{
       res.status(200).send({"status":"ok"});
     }
    }
  );
});

我收到错误:

{ title: 'dogs', _id: 564f1d1444f30e0d13e84e7b, cats: [] }
undefined
ERROR:  { [CastError: Cast to undefined failed for value "[object Object]" at path "apps"]
  message: 'Cast to undefined failed for value "[object Object]" at path "apps"',
  name: 'CastError',
  type: undefined,
  value: [{"title":"dogs","_id":"564f1d1444f30e0d13e84e7b","cats":[]}],
  path: 'apps' }

我做错了什么?

修改

question中找到答案 实际上我需要导入模式而不是对象

//account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var ApplicationSchema = require('./application.js').schema; //<-- .schema was added

var Account = new Schema({
    username: String,
    password: String,
    apps: [ApplicationSchema]
});

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('Account', Account);

1 个答案:

答案 0 :(得分:5)

要在Application模型的应用嵌入式文档字段中保存Account引用,请在保存时按_id模型的回调中的Application值:

<强> account.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Application = require('./application.js');

var Account = new Schema({
    username: String,
    password: String,
    apps: [{type: Schema.Types.ObjectId, ref: 'Application'}]
});

Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);

<强> app.js

app.post('/application', function(req, res){
    var name = req.user.username;
    var newApp = new Application({
        title: req.body.title
    }); 
    console.log(newApp);

    newApp.save(function (err){
        if (err) return handleError(err);

        Account.findOne({ username: name }, function (err, doc){
            if (err) return handleError(err);
            doc.apps.push(newApp._id);        
            doc.save();
            res.status(200).send({"status":"ok"});
        });
    });
});

或使用承诺:

const handleError = err => console.error(err);

app.post('/application', (req, res) => {
    const name = req.user.username;
    const newApp = new Application({
        title: req.body.title
    }); 

    newApp.save().then(result => (
        Account.findOneAndUpdate(
            { "username": name },
            { "$push": { "apps": result._id } }
        )
    )
    .then(result => res.status(200).send({"status":"ok"}))
    .catch(handleError);        
});