目前我正在尝试在 api 调用中更新两个不同的用户架构。
第一个模式是登录用户模式,我们给它起一个名字 = Tom
第二个模式是注册该应用程序的其他用户,我们给它一个名称 = John
架构代码
架构.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false },
followers: [{ type: Schema.Types.ObjectId, ref: 'User'}],
following: [{ type: Schema.Types.ObjectId, ref: 'User'}],
followersCount: Number,
followingCount: Number
});
module.exports = mongoose.model('User', UserSchema);
api名称是'/follow/:user_id',我想要实现的是.每当用户 Tom 关注其他用户(例如 John)时,Tom 的下列的字段将与 John 的一样更新follower field.
我当前的尝试(req.decoded.id是登录用户)
api.js
// The first way
apiRouter.post('/follow/:user_id', function(req, res) {
User.findOneAndUpdate(
{
_id: req.decoded.id,
following: { $ne: req.params.user_id }
},
{
$push: { following: req.params.user_id},
$inc: { followingCount: 1}
},
function(err, currentUser) {
if (err) {
res.send(err);
return;
}
console.log(currentUser);
});
User.findOneAndUpdate(
{
_id: req.params.user_id,
followers: { $ne: req.decoded.id }
},
{
$push: { followers: req.decoded.id },
$inc: { followersCount: 1}
}, function(err, user) {
if(err) {
res.send(err);
return;
}
res.json({
message: "Successfully followed"
});
}
)
});
//Second way
apiRouter.post('/follow/:user_id', function(req, res) {
// find a current user that has logged in
User.update(
{
_id: req.decoded.id,
following: { $ne: req.params.user_id }
},
{
$push: { following: req.params.user_id},
$inc: { followingCount: 1}
},
function(err) {
if (err) {
res.send(err);
return;
}
User.update(
{
_id: req.params.user_id,
followers: { $ne: req.decoded.id }
},
{
$push: { followers: req.decoded.id },
$inc: { followersCount: 1}
}
), function(err) {
if(err) return res.send(err);
res.json({ message: "Successfully Followed!" });
}
});
});
双方都有问题,
第一种方法:问题是,“无法设置已发送的标头”,因为一个 api 调用中有两个单独的猫鼬查询,它响应两次,这就是我收到该错误的原因。
第二种方法:问题是下列的登录用户(Tom)的字段会更新,而其他用户的字段会更新追随者字段(约翰)返回 null。我控制台记录这两个值,并使用 POSTMAN chrome 应用程序对其进行测试。
借给我你们的想法吧伙计们!