将ObjectId推送到Mongoose

时间:2017-11-19 22:26:33

标签: mongodb express mongoose

(基础库CRUD应用程序)

我正在尝试创建一个包含有关给定书籍的全局数据的文档,然后在用户文档中,将新创建的书籍的ObjectId添加到包含属于该用户的所有书籍的数组中。

我的应用程序中有三个数据模型:



var userSchema = new mongoose.Schema({
    name: String,
    password: String,
    email: String,
    books: [BookInstanceSchema],
    shelves: [String]
});

var bookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author: {
        type: String,
        required: true
    },
    description: String,
    pageCount: Number,
    ISBN: String,
    googleID: String,
    thumbnail: String,
    publisher: String,
    published: String,
});

var BookInstanceSchema = new mongoose.Schema({
    bookId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Book'
    },
    userReview: String,
    userRating: {
        type: Number,
        get: v => Math.round(v),
        set: v => Math.round(v),
        min: 0,
        max: 4,
        default: 0
    },
    shelf: String
});




User模型包含一个嵌套的BookInstances数组,其中包含特定于用户的数据,例如给定书籍的评级或评论。 bookInstance反过来包含对书籍全局数据的引用,以避免重复不特定于任何用户的数据。

我要做的是首先保存图书的全局数据(从而生成一个_id),完成后,在给定用户的图书数组中保存一个包含该_id的bookInstance:



router.post('/save/:id', function(req, res) {

    var url = encodeurl('https://www.googleapis.com/books/v1/volumes/' + req.params.id);

    request(url, function(err, response, data) {

        parsedData = JSON.parse(data);

        var newBook = {
            title: parsedData.volumeInfo.title,
            author: parsedData.volumeInfo.authors[0],
            description: parsedData.volumeInfo.description,
            pageCount: parsedData.volumeInfo.pageCount,
            ISBN: parsedData.volumeInfo.description,
            googleID: parsedData.id,
            publisher: parsedData.volumeInfo.publisher,
            published: parsedData.volumeInfo.publishedDate,
            thumbnail: parsedData.volumeInfo.imageLinks.thumbnail
        };

        Book.create(newBook, function(err, newBook) {
            if (err) {
                console.log(err);
            }
            else {

                console.log(newBook._id);
                console.log(mongoose.Types.ObjectId.isValid(newbook._id));

                User.findByIdAndUpdate(req.session.id, {
                    $push: {
                        "books": {
                            bookId: newBook._id,
                            userRating: 0,
                            userReview: ''
                        }
                    }
                },
                {
                    upsert: true
                },
                function(err, data){
                    if(err) {
                        console.log(err);
                    }
                    else {
                        res.redirect('/');
                    }
                });
            }
        });
    });
});




I'm getting the error: 

  message: 'Cast to ObjectId failed for value "hjhHy8TcIQ6lOjHRJZ12LPU1B0AySrS0" at path "_id" for model "User"',
  name: 'CastError',
  stringValue: '"hjhHy8TcIQ6lOjHRJZ12LPU1B0AySrS0"',
  kind: 'ObjectId',
  value: 'hjhHy8TcIQ6lOjHRJZ12LPU1B0AySrS0',
  path: '_id',
  reason: undefined,

每次,错误中的值(在这种情况下,jhHy8T ......)都不同于newBook._id我尝试推入数组:

console.log(newBook._id); // 5a120272d4201d4399e465f5
console.log(mongoose.Types.ObjectId.isValid(newBook._id)); // true

在我看来,我的用户更新声明出现了问题:

User.findByIdAndUpdate(req.session.id, {
$push: {
    "books": {
        bookId: newBook._id,
        userRating: 0,
        userReview: ''
    }
}...

有关如何更好地整理数据的任何帮助或建议表示赞赏。谢谢!

0 个答案:

没有答案