ObjectId未保存在数组中

时间:2020-04-14 20:10:52

标签: javascript mongodb express mongoose

https://thinkster.io/tutorials/node-json-api/adding-favoriting-functionality

我正在按照本教程进行操作,但是无法使偏爱功能起作用。 非常感谢您的帮助。

UserSchema:

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

1 个答案:

答案 0 :(得分:0)

感谢@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();
};

再次感谢您的帮助,乔!

相关问题