我想使用Mongoose和Express为数组添加值。
router.put( '/projectUser/:id', function( req, res ) {
return ProjectProfile.findById( req.params.id, function( err, project ) {
project.users.push(req.body.user);
return project.save( function( err ) {
if( !err ) {
console.log( 'Project Users updated' );
return res.send( project );
} else {
console.log( err );
return res.send('ERROR');
}
});
});
});
当我这样做时,我收到以下错误
{ [ValidationError: Project validation failed]
message: 'Project validation failed',
name: 'ValidationError',
errors:
{ 'users.-1._id':
{ [CastError: Cast to ObjectID failed for value "EXAMPLE-STRING" at path "_id"]
message: 'Cast to ObjectID failed for value "EXAMPLE-STRING" at path "_id"',
name: 'CastError',
kind: 'ObjectID',
value: 'EXAMPLE-STRING',
path: '_id' } } }
项目架构
var ProjectProfileSchema = new mongoose.Schema({
projectName: String,
productName: String,
users: [{user:'string'}]
});
值EXAMPLE-STRING是标准字符串。它需要一个Mongoose _id吗?
答案 0 :(得分:1)
您要推送到project.users
数组的对象应该是User
文档(假设这是您的模型的名称),或者它应该是ObjectId
(或者表示一个的字符串,属于数据库中的User
文档。
根据req.body.user
的确切含义,这可能有效:
project.users.push(new User(req.body.user));