问题
I'm trying to update a document which contains 2 other documents. To achieve this task, I use findOneAndUpdate, but mongoose throws me a CastError (Cast to ObjectId failed).
My models:
user.js
var userSchema = new Schema({
email: String,
info: {
type : Schema.ObjectId,
required : true,
ref : 'Info'
}
});
module.exports = mongoose.model('User', userSchema);
info.js
var infoSchema = new Schema({
firstname: String,
lastname: String
});
module.exports = mongoose.model('Info', infoSchema);
My query:
var tmp = {
email: req.body.email,
info: {
name: req.body.info.name
}
};
User.findOneAndUpdate({
_id: req.params.id
}, tmp, {
upsert: false,
new: true
}).exec(function(err, doc) {
/* check errors */
/* send response */
});
What am I doing wrong? Are my models poorly set?
回答1:
CastError: Cast to ObjectId failed
The type of info is Schema.ObjectId, whereas one object
info: {
name: req.body.info.name
}
is passed into it as ObjectId, as result, it failed.
Here maybe one work around.
var new_info = new Info({
firstname: req.body.info.name.firstname, //
lastname: req.body.info.name.lastname //
});
new_info.save(function(err, doc) {
if (err)
console.log(err);
else {
var tmp = {
email: req.body.email,
info: doc._id
}
User.findOneAndUpdate({
_id: req.params.id
}, tmp, {
upsert: false,
new: true
}).exec(function(err, doc) {
//
});
}
});
来源:https://stackoverflow.com/questions/34889271/mongoose-findoneandupdate-nested-documents