如何从一个的NodeJS猫鼬聚集查询获取数据
猫鼬查询获取正确的结果,但我无法访问数据。
我想当前的最大ID在数据库中,由1递增值和数据保存到数据库
// add a new book
router.route('/books/add').post(jsonParser, (req, res) => {
Book.aggregate([{ $group: { _id: "id", id: { $max: "$id" } } }], (err, books) => {
if (!books)
return next(new Error("Could not load book!"))
else {
let book = new Book(req.body);
// log the max id returned, currently returns undefined
console.log("Id found ", books.id);
book.id = books.id + 1;
console.log("BookId ", book.id);
res.status(200).json({ 'book': 'Added successfully!' });
// book.save().then(book => {
// res.status(200).json({ 'book': 'Added successfully!' });
// }).catch(err => {
// res.status(400).send('Failed to create new record.');
// });
}
});
});
console.log(books.id)
返回undefined
而console.log(books)
不告诉我的结果是[ { _id: 'id', id: 5 } ]
。我想要做的就是标识即5,我该怎么做呢?谢谢。
该汇总查询结果是一个数组,而您必须使用零的索引来获得它是一个对象包含你的结果的第一要素。尝试这个:
console.log(books[0].id)
如何从一个的NodeJS猫鼬聚集查询获取数据
猫鼬查询获取正确的结果,但我无法访问数据。
我想当前的最大ID在数据库中,由1递增值和数据保存到数据库
// add a new book
router.route('/books/add').post(jsonParser, (req, res) => {
Book.aggregate([{ $group: { _id: "id", id: { $max: "$id" } } }], (err, books) => {
if (!books)
return next(new Error("Could not load book!"))
else {
let book = new Book(req.body);
// log the max id returned, currently returns undefined
console.log("Id found ", books.id);
book.id = books.id + 1;
console.log("BookId ", book.id);
res.status(200).json({ 'book': 'Added successfully!' });
// book.save().then(book => {
// res.status(200).json({ 'book': 'Added successfully!' });
// }).catch(err => {
// res.status(400).send('Failed to create new record.');
// });
}
});
});
console.log(books.id)
返回undefined
而console.log(books)
不告诉我的结果是[ { _id: 'id', id: 5 } ]
。我想要做的就是标识即5,我该怎么做呢?谢谢。
该汇总查询结果是一个数组,而您必须使用零的索引来获得它是一个对象包含你的结果的第一要素。尝试这个:
console.log(books[0].id)