1。我正在尝试通过如下所示的below.js节点查询数据库“ teamautomation”中的“ radar_life_cycle”集合
2。我创建了相应的模型 ,通过猫鼬连接到mongodb成功,没有错误,但我得到了一个空列表。
[]
是一个空列表,但我可以看到数据库中有记录,有人可以提供有关此处可能出问题的指南吗?app.js
const express = require("express");
const mongoose = require("mongoose");
const Radar_life_cycle = require("./models/radar_life_cycle");
const app = express();
mongoose
.connect(
"mongodb://username:password@1x.xxx.xxx.x:27017/wifiautomation"
)
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
app.get("/api/radars", (req, res, next) => {
Radar_life_cycle.find({ orgRadar: "51918661" }).then(documents => {
res.status(200).json({
message: "Posts fetched successfully!",
posts: documents
});
});
});
模型/ radar_life_cycle
const mongoose = require('mongoose');
const radar_life_cycle_Schema = mongoose.Schema({
Delivered: String,
orgRadar: String,
root_build: String,
inserted_by: String,
milestone: String,
applicable_chipsets: [String],
project_tag: String,
gerrits:String,
inserted_on:Date,
SDK:String
});
module.exports = mongoose.model('radar_life_cycle', radar_life_cycle_Schema);
输出:-
terminal$ nodemon server.js
[nodemon] 1.14.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
(node:17500) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Connected to database!
{"message":"Posts fetched successfully!","posts":[]}
预期输出:-
{"message":"Posts fetched successfully!","posts":should include the corresponding records}
数据库中文档的截图:
答案 0 :(得分:1)
以这种方式尝试Schema可能对集合没有很好的参考
const { Schema } = require('mongoose');
const radar_life_cycle_Schema= new Schema({
Delivered: String,
orgRadar: String,
root_build: String,
inserted_by: String,
milestone: String,
applicable_chipsets: [String],
project_tag: String,
gerrits:String,
inserted_on:Date,
SDK:String
},
{
collection: 'radar_life_cycle',
timestamps: { createdAt: true, updatedAt: true },
});
module.exports = mongoose.model('radar_life_cycle', radar_life_cycle_Schema);
答案 1 :(得分:0)
app.get("/api/radars", (req, res, next) => {
Radar_life_cycle.find({ orgRadar: "51918661" }).then(documents => {
res.status(200).json({
message: "Posts fetched successfully!",
posts: documents[0]
});
});
});
find
方法将查找数据库中的所有文档,在这种情况下,似乎只有一个...如果有更多文档,您可以在上面更新代码并使用循环访问文档。