在MongoDB中创build新logging时,如何将多个项目保存到数组字段?
我有以下用于“组”集合的模式。 我希望能够创build此logging,并在第一次创build时将任意数量的“成员”推送到此组。 保存logging时,我无法获取“成员”字段。 所有其他字段保存没有问题。
var groupSchema = mongoose.Schema({ creator : String, name : String, members: [{ type: String, ref: 'User' }], created : { type: Date, default: Date.now } }); app.post('/create-group', function(req, res) { //req.body.users = ['12345', '23456', '34567'] for example var group = new Group({ name : req.body.group_name, creator : req.user._id, members: {$push: req.body.users} }); group.save(function (err, data) { if (!err) { return res.json(data); } }); });
即使所有其他字段保存正确,也不会将结果存储在“成员”中。 我究竟做错了什么?
编辑
在你的模式中,当你写ref:“User”时,这意味着你必须提供一个用户模式,而不是一个string或整数。 如果你只是想要一个string数组,你可以简单地使用[String]。
根据文档,你必须使用一个objectID http://mongoosejs.com/docs/populate.html
members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
在上面提供的链接中,您将能够检查如何保存您的组并添加任意数量的成员。
members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
正如Su4p指出的那样。 不要担心包含string而不是ObjectIds的req.body.users
。 mongoose
会将string转换成对象ID。 还有一个错误,
members: {$push: req.body.users}
应该
members: req.body.users
$push
是一个更新操作符。 这并不意味着分配数组。
- 在Node.js上的Express中扩展View类
- Ajax使用express和JQuery刷新部分视图?
- 在使用Angular的单页面应用程序引擎时,依靠socket.io/express.io中的“disconnect”事件
- 使用Node.js和Express进行简单的API调用
- 如何在nodejs / express中发布大量的json数据(不是文件)
- 无法使用Express 3.0在Node.js中设置cookie'expires'或'maxAge'
- 在nodejs中侦听http服务器时出现Express模块错误
- Nodejs或ExpressJS Windows身份validation
- Passport本地策略完成callback不会传递错误json消息