mongoose CastError:在路径“apps”处为值“[object Object]”转换为未定义失败

Posted

技术标签:

【中文标题】mongoose CastError:在路径“apps”处为值“[object Object]”转换为未定义失败【英文标题】:mongoose CastError: Cast to undefined failed for value "[object Object]" at path "apps" 【发布时间】: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);

【问题讨论】:

【参考方案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'],在这种情况下,答案就足够了。

以上是关于mongoose CastError:在路径“apps”处为值“[object Object]”转换为未定义失败的主要内容,如果未能解决你的问题,请参考以下文章

mongoose.js CastError:在路径“未定义”处为值“[object Object]”转换为数字失败

Mongoose:CastError:对于模型“”的路径“_id”处的值“”,转换为 ObjectId 失败

mongoose CastError:在路径“apps”处为值“[object Object]”转换为未定义失败

CastError:TypeScript REST 和 Mongoose 中路径“_id”处值“1225589795”的值“1225589795”转换为 ObjectId 失败

Mongoose CastError:模型“Post”的路径“_id”处的值“未定义”转换为 ObjectId 失败

Mongoose CastError:模型“Task”的路径“_listId”的值“:listId”转换为 ObjectId 失败