【发布时间】:2015-03-21 23:51:30
【问题描述】:
目前我想做的是,一旦用户登录,他可以转到任何用户的网址并关注他们。我遇到了这个问题
TypeError: Object { _id: 54bd6b90b7d4cc8c10b40cbd,
name: 'Johnny',
username: 'batman',
__v: 0,
following: [],
followers: [] } has no method 'save'
schema.js
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false },
level: String,
followers: [{ type: Schema.Types.ObjectId, ref: 'User'}],
following: [{ type: Schema.Types.ObjectId, ref: 'User'}]
});
module.exports = mongoose.model('User', UserSchema);
api.js
// this is where I'm Stuck ( Should I use put or post? for best practices)
.post(function(req, res) {
// find a current user that has logged in
User.find({ _id: req.decoded.id }, function(err, user) {
// simply follow the user by matching the id
user.following = req.params.user_id;
// save to the database ( The problem )
user.save(function(err) {
if(err) res.send(err);
res.json({ message: "Successfully followed!"})
})
});
})
问题出在 .post 中,因为我无法保存。我应该怎么做才能让它保存到数据库中?
【问题讨论】:
-
User
.findOne()as.find()返回一个数组,而一个数组没有.save()方法。你真的应该使用.update()。您的代码存在并发问题。 -
也许你应该使用
.findOne()。 -
@NeilLunn 能否解释一下并发问题?
-
@NeilLunn 这是最佳实践吗?
-
当您
.find()某物时,您会从数据库中检索它。如果您进行更改然后.save()文档,其他人可能已经更改了数据库中的文档,并且这些更改将丢失。.update()和类似的方法可以避免这种情况。
标签: javascript node.js mongodb mongoose mongodb-query