javascript - ObjectId 未保存在数组中
问题描述
https://thinkster.io/tutorials/node-json-api/adding-favoriting-functionality
我正在按照教程进行操作,但无法使收藏功能正常工作。我将非常感谢一些帮助,谢谢。
用户架构:
var UserSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9_]+$/, 'is invalid'], index: true},
email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
bio: String,
image: String,
hash: String,
salt: String,
following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }]
}, {timestamps: true});
用户收藏文章的方法:
UserSchema.methods.favorite = function(id){
if(this.favorites.indexOf(id) === -1){
console.log("id is: ", id) //
this.favorites.concat(id);
}
console.log("this favorites is:", this.favorites);
return this.save();
};
发布请求以收藏文章:
router.post('/:article/favorite', auth.required, function(req, res, next) {
var articleId = req.article._id;
User.findById(req.payload.id).then(function(user){
if (!user) { return res.sendStatus(401); }
return user.favorite(articleId).then(function(){
return req.article.updateFavoriteCount().then(function(article){
return res.json({article: article.toJSONFor(user)});
});
});
}).catch(next);
});
卷曲请求:
curl --location --request POST 'http://localhost:3000/api/articles/how-to-train-your-dragon-m06dim/favorite' \
--header 'Content-Type: application/json' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlOTIxMTQ3ZWYxZjkxMzcwZjEwMDkwNiIsInVzZXJuYW1lIjoidGl5YXl1IiwiZXhwIjoxNTkyMDIzODMxLCJpYXQiOjE1ODY4Mzk4MzF9.pIA7RVgVbRI6-2IQzW2vptEzwiZrqCroz8-SdGRNEF8' \
--data-raw ''
在服务器日志中,您可以看到 user.favorites 的 console.log 保持为空:
Listening on port 3000
Mongoose: users.ensureIndex({ username: 1 }) { unique: true, background: true }
Mongoose: articles.ensureIndex({ slug: 1 }) { unique: true, background: true }
Mongoose: users.ensureIndex({ email: 1 }) { unique: true, background: true }
Mongoose: articles.findOne({ slug: 'how-to-train-your-dragon-m06dim' }) { fields: undefined }
Mongoose: users.find({ _id: { '$in': [ { inspect: [Function: inspect] } ] }}) { fields: undefined }
Mongoose: users.findOne({ _id: { inspect: [Function: inspect] } }) { fields: undefined }
id is: ObjectID { _bsontype: 'ObjectID', id: '^•C\u0006’ï`w2%\u0014f' }
this favorites is: []
Mongoose: users.count({ '$and': [ { username: 'tiyayu' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: users.count({ '$and': [ { email: 'tiyayu@yaya.com' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: users.update({ _id: { inspect: [Function: inspect] } }) { '$set': { updatedAt: { inspect: [Function: inspect] } } }
Mongoose: users.count({ favorites: { '$in': [ { inspect: [Function: inspect] } ] }}) {}
Mongoose: articles.count({ '$and': [ { slug: 'how-to-train-your-dragon-m06dim' }, { _id: { '$ne': { inspect: [Function: inspect] } } } ]}) {}
Mongoose: articles.update({ _id: { inspect: [Function: inspect] } }) { '$set': { updatedAt: { inspect: [Function: inspect] } } }
POST /api/articles/how-to-train-your-dragon-m06dim/favorite 200 126.823 ms - 423
解决方案
感谢@Joe的评论,我能够解决这个问题:
我知道我已经用concat方法替换了已弃用的push方法,但我没有正确执行:
myArray.push(myObject); //breaks on DocumentDB with Mongo API because of deprecated $pushAll
类似于:
myArray = myArray.concat([myObject]);
所以我的固定方法是这样的:
UserSchema.methods.favorite = function(id){
if(this.favorites.indexOf(id) === -1){
this.favorites = this.favorites.concat([id]);
}
return this.save();
};
再次感谢您的帮助乔!
推荐阅读
- amazon-web-services - 安装 kube-prometehus-stack 卡在钩子并发症上
- javascript - JavaScript IF 语句和 While 循环无法正常工作
- python - (Python)如何将 3 个递减列表合并为一个递减列表?
- output - uniq -u 什么都不返回
- javascript - JavaScript 高阶函数中的附加参数如何工作?
- python - 由于 Dash 无法运行 Django 本地服务器
- docker - 服务之间的本地通信
- python - 使用子进程使用 python 运行命令
- django - 如何设置gunicorn
- reactjs - react js动态修改head中的link rel="stylesheet"