使用 Express 将新项目添加到 MongoDB 数据库的开头

时间:2020-12-28 06:51:09

标签: database mongodb api express mongoose

我有一个存储项目列表的 mongoDB 数据库:

[{"_id":"0", "a": "b"}, {"_id":"1", "a": "c"}]

要通过 POST 请求向数据库添加新项目,我使用的是 Express 路由器和 Mongoose:

router.post('/', (req, res) => {
    const newItem = new Item({a: req.body.a})
    newItem.save()
    .then(item => res.json(item))
})

之后,数据库看起来像:

[{"_id":"0", a: "b"}, {"_id":"1", a: "c"}, {new item}]

有没有办法像这样将新项目添加到前面?

[{new item}, {"_id":"0", "a": "b"}, {"_id":"1", "a": "c"}]

感谢任何想法。

1 个答案:

答案 0 :(得分:0)

如果你使用猫鼬

Item.find({},(err,data)=>{
   if(err){
     res.send(err);
     console.log(err);
   }
   else{
     res.send(data);
   }
})```
this is the way to fetch all data from collection using mongoose.