Mongoose更新ref对象
Mongoose update ref objects?
很抱歉我的英语不好
我使用node.js+express.js+mongoose.js我在mongoose中有这个组模式:
var groupSchema = new mongoose.Schema({
name: String,
users: [{type: mongoose.Schema.ObjectId, ref: 'User'}],
posts: [{type: mongoose.Schema.ObjectId, ref: 'Post'}]
});
和这个模式给用户:
var userSchema = new mongoose.Schema({
login: { type: String, unique: true, lowercase: true },
password: String,
unread: [{type: mongoose.Schema.ObjectId, ref: 'Post'}]
});
组具有与此组相关的用户列表和与此组关联的帖子列表
我想要实现的:Group1
具有用户Mike
、John
和Jane
当用户Mike
创建新帖子时:
1)我找到当前组并选择与该组相关的用户(Group1
和用户Mike
、John
和Jane
)
2)对于用户John
和Jane
,我必须在unread
字段中设置创建的帖子。(让这个知道,哪个帖子用户还没有阅读)
这是正确的吗?如果是,我如何更新ref文档中的未读字段?
我试着这样做:
例如:组的url:http://localhost:3000/group/first
app.get('/group/:name', groups.getGroupPage);
app.post('/group/:name', posts.postCreate);
Posts.js
var Group = require('../models/group');
var User = require('../models/user');
var Post = require('../models/post');
exports.postCreate = function(req, res) {
var post = new Post({
title: req.body.p_title,
content: req.body.p_content,
author: req.user
});
Group
.update({ name: req.params.name }, {upsert:true}, { "$push": { "users.$.unread": post._id } })
.populate('users')
.exec(function(err,group) {
if (err) res.json(err)
console.log(group);
}
);
}
谢谢你的帮助。
您的编码风格与我的有点不同,但我的做法如下:
exports.postCreate = function(req, res) {
//Create a new post
var newPost = new Post({
title: req.body.p_title,
content: req.body.p_content,
author: req.user
});
//Save the new post
newPost.save(function(err) {
if (err) {
res.json(err);
}
});
//Find the group with the name and populate the users field
Group.findOne({ name: req.params.name })
.populate('users')
.exec(function(err, group) {
if (err) {
res.json(err);
console.log(group);
}
if (group) {
//If group is found loop through the users
for (var i = o; i < group.users.length; i++) {
//Check if the current user is somebody else as the author
if (group.users[i]._id != req.user._id) {
//Push and save the new post to every user in the group
//We push the _id of the post because we are using references
group.users[i].unread.push(newPost._id);
group.users[i].save(function(err) {
if (err) {
throw err;
}
});
}
}
} else {
//Do what you need to do if group hasn't been found
}
});
};
这段代码假设您的req.user
字段被填充为User模式。
此代码未经测试。所以请调试它。:)
相关文章:
- 引用对象中的通用值
- jQuery匹配JSON对象的部分文本
- 节点导出返回一个空对象
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 全局变量和全局对象的属性之间有什么区别吗
- 比较从函数和生成的日期对象
- Javascript,访问一个主要对象模块模式中的每个对象
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 调整窗口大小时,可拖动的对象会出现在容器外部
- 如何使用javascript从主svg对象动态创建svg视图框
- 如何使用json将对象列表从java转换为javascript
- 序列化数据属性中对象的最可靠方法
- 如何访问声音管理器2创建的声音对象
- Mongoose更新ref对象
- Mongoose填充包含ref的对象数组
- 从Firebase数据库中删除ref的子对象
- 从几个ref对象数组中的值求和
- 填充()ref嵌套在对象数组中