mongoose铸错误_id
我想保存一个新用户并添加一些组作为参考。 该组从数据库加载。
var userSchema = new Schema({ email: {type: String, 'default': '', index: {unique: true, dropDups: true}}, password: String, accessToken: String, registerDate: { type: Date, 'default': Date.now}, groups: [{type: ObjectId, ref:'Group'}] }); var groupSchema = new Schema({ name: {type: String, 'default': '', index: {unique: true, dropDups: true}} }); exports.register = function(req, res, next){ var userToRegister = req.body; var newUser = new User(); Group.find({name:"User"}, function(err, group){ if(err){ res.send("no User-group found"); } newUser.set('groups', [group]); newUser.set('email', userToRegister.email); newUser.set('password', userToRegister.password); newUser.save(function(err){ if(err){ res.end("error at saving user", 500); } res.end(JSON.stringify(newUser)); }); }); };
但是我得到以下错误:
message "Cast to ObjectId failed for value "{ _id: 52f6b49e13bdfa901b5a64d3, __v: 0, name... (length: 108)" name "CastError" path "groups" stack undefined type "ObjectId"
正如我所看到的,这是一个有效的ObjectId。 那么哪里可能是错误?
解:
使用:Group.findOne(…)或:newUser.set('groups',[group [0]]);
.find返回数组。 使用组[0]或使用findOne()。
newUser.set('groups', [group[0]]);
- 护照 – 本地 – mongoosechangePasswordfunction
- Mongoose或MongoDB的架构定义?
- Mongoose可选的嵌套属性 – 检查null / undefined?
- 客户端生成的JSON存储在MongoDB服务器端,application / json不能正确parsing?
- MongoDB计数不同的值?
- 有没有办法使用查询生成器使用Mongoose中间件?
- 使用asynchronouswhile循环创build和插入文档
- 使用分布式数据库为node.js(MongoDB?)进行事件日志logging
- 如何使用swift 3 for iOS连接到MEAN stack REST api