[英]Mongoose update ref objects?
对不起,我的英语不好。
我使用node.js + express.js + mongoose.js我在猫鼬中有以下模式用于组:
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
字段中设置创建的帖子。 (要知道,哪个帖子用户尚未阅读)。
这是正确的吗? 如果是,我如何更新参考文件中的未读字段?
我试图做到这一点:
例如:群组的网址: 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模式。
此代码未经测试。 因此,请对其进行调试。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.