I have a nested schema defined with 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);
and
//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);
Now if I try to push to apps
which is an array in account
like this:
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"});
}
}
);
});
I get the error:
{ 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' }
what am I doing wrong?
EDIT:
Found the answer in this question Practically I need to import the schema not the object
//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);