node.js - Mongoose CastError : Cast to undefined failed for value "[object Object]" at path "apps"

标签 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);

最佳答案

要在 Account 模型的应用嵌入文档字段中保存 Application 引用,将 _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"});
        });
    });
});

或者使用 promises 作为:

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

关于node.js - Mongoose CastError : Cast to undefined failed for value "[object Object]" at path "apps",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33828182/

相关文章:

node.js - 如何处理我的 expressjs 应用程序中的意外错误以避免停机?

javascript - 在 Node.js 中,如何防止客户端从我的网站打开多个实例

mongodb - 如何使用 django-nonrel 和 mongodb 进行自定义查询

mongodb - docker 在哪里存储我的 MongoDB 数据?

node.js - 全新 express 项目 doctype 5` is deprecated, you must now use ` doctype html` 上的错误

mysql - 当有人搜索 NULL 对象时的响应

mongodb - $project mongodb 聚合中的 $regex

node.js - 如何在 Mongoose 中创建和使用枚举

node.js - 有哪些开源 Node.js CI 项目?

javascript - Node.js:遇到 mocha 问题并期望 to.throwError