【问题标题】:mongoose CastError: Cast to undefined failed for value "[object Object]" at path "apps"mongoose CastError:在路径“apps”处为值“[object Object]”转换为未定义失败
【发布时间】:2016-02-23 00:42:16
【问题描述】:

我有一个用 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);

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    要将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);        
    });
    

    【讨论】:

    • 是的,我也试过了,它有效!请看我的编辑。我现在意识到这是将该字段声明为 id 数组而不是实际对象。即使我试图做不同的事情,我也会接受答案。谢谢
    • @Sanandrea 不用担心,很高兴这一切最终都为你解决了 :)
    • 我注意到由于一些代码混合,我没有意识到为了让您的建议生效,我必须更改:apps: [ObjectId] in account.js。其中 ObjectId 是 var ObjectId = Schema.ObjectId。所以请更新你的答案。
    • @Sanandrea Yea,也注意到了这一点,最初认为您已将参考嵌入为 apps: [{type: Schema.Types.ObjectId, ref: 'Application'}],在这种情况下,答案就足够了。
    猜你喜欢
    • 2015-11-16
    • 2013-02-06
    • 1970-01-01
    • 2013-06-17
    • 2017-05-26
    • 2018-03-17
    • 2021-06-05
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多