我在Node.js中创建了一个带有mongoose的API。我将数据保存在一个集合中,它提供了一些来自其他集合对象的引用:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const transactionSchema = new Schema({
status: String,
_user: { type: Schema.Types.ObjectId, ref: 'User' },
_borne: { type: Schema.Types.ObjectId, ref: 'Borne' },
createdAt: Date,
updatedAt: Date
});
当我对事务进行查询时,我会得到Borne对象而不是它的id,因为它保存在我的数据库中。我没有直接将它保存为Borne对象,因为某些更改可能出现在我的Borne(或用户)对象中,我希望它保存在每个Transaction对象上。
所以我尝试使用虚拟或路径(覆盖),但它并没有改变我的输出,我也不知道它是否是正确的方法:
// In this example, I try to change the status output by "new status" to test if it works, and it doesn't
transactionSchema.path('status')
.get(function(value) {
return "new status";
})
});
输出与以前相同。
Populate
是解决方案,但不起作用目前,我正在我的index.js
文件中加载我的模型:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const apn = require('apn');
const keys = require('./config/keys');
require('./app/models/Borne');
require('./app/models/User');
require('./app/models/Transaction');
require('./app/models/Comment');
require('./app/models/Notification');
const app = express();
const apnProvider = new apn.Provider(keys.apns.options);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect(keys.mongoURI, (err, database) => {
if (err) return console.log(err);
require('./app/routes')(app);
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log('We are live on ' + PORT);
});
});
然后,这是一个模型的例子:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const transactionSchema = new Schema({
status: String,
details: {
amount: { type: Number }, // money
quantity: { type: Number }, // power consumed
date: { type: Date },
city: { type: String }
},
logs: [
{
state: String,
date: Date
}
],
_user: { type: Schema.Types.ObjectId, ref: 'User' },
_borne: { type: Schema.Types.ObjectId, ref: 'Borne' },
createdAt: Date,
updatedAt: Date
});
mongoose.model('transactions', transactionSchema);
最后,我在这里呼叫populate
。它没有用:
const mongoose = require('mongoose');
const User = mongoose.model('users');
const Transaction = mongoose.model('transactions');
const Borne = mongoose.model('bornes');
const Comment = mongoose.model('comments');
module.exports = app => {
app.get('/v1/user/:id/transactions', async (req, res) => {
const ObjectID = require('mongodb').ObjectID;
var id = req.params.id;
var existingUser;
if (req.params.id == 'me' && req.user) {
id = req.user.id;
existingUser = req.user;
} else {
existingUser = await User.findOne({ _id: new ObjectID(id) });
}
if (existingUser) {
const transactions = await Transaction.find({
_user: new ObjectID(id),
status: { $nin: ['booked', 'charging', 'charged', 'left'] }
}).populate('_user').populate('_borne').sort({ updatedAt: -1 });
// ...
res.status(200);
res.send({
statusCode: 200,
data: transactions
});
}
});
};
答案 0 :(得分:2)
根据MongoDB Documentation,如果你想获得引用所指向的对象,你必须“手动”进行第二次查询。
但是Mongoose
提供了populate
方法,它允许您用正确的文档替换引用。
人口是自动替换指定的过程 文档中包含来自其他集合的文档的路径。
所以,在你的情况下,你可以这样做:
var transactionModel = mongoose.model('Transaction', transactionSchema);
transactionModel
.find({})
.populate('_user')
.populate('_borne')
.exec((err, transaction) => {
if (err) return handleError(err);
// deal with your transaction
});
我刚读过你的编辑,你能为我试试吗:
删除require('./app/models/xxx')
文件中的所有index.js
。
在模特的最后:
module.exports = mongoose.model('xxx', xxxSchema);
然后在你的路线/控制器中:
const User = require('/app/models/users');
const Borne = require('/app/models/borne');
const Transaction = require('/app/models/transaction');
因此,您的模型与模式同时创建,并且您确定这是正确的顺序。
希望它有所帮助,
最好的问候
答案 1 :(得分:0)
我认为有一个快速而强大的查询,你应该看看Aggregate Query与moongodb。
查询事务集合(匹配正确的_id),然后展开_user属性,查找用户集合(类似于SQL中的JOIN),展开_born集合,查找生成的集合。
看起来有点像这样复杂,但它非常强大而且速度很快。