mongoose - 如何在 getter 中获取对象而不是对象引用?

cus*_*mar 4 javascript mongoose mongodb node.js mongoose-schema

我在 Node.js 中使用 mongoose 创建了一个 API。我将我的数据保存在一个集合 Transactions 中,它提供了来自其他集合对象的一些引用:

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
});
Run Code Online (Sandbox Code Playgroud)

当我查询交易时,我会得到 Borne 对象而不是它的 id,因为它保存在我的数据库中。我不直接将它保存为 Borne 对象,因为我的 Borne(或 User)对象中可能会出现一些更改,我希望将其保存在每个 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";
    })
});
Run Code Online (Sandbox Code Playgroud)

输出与之前相同。


编辑: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);
  });
});
Run Code Online (Sandbox Code Playgroud)

然后,这是一个模型示例:

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);
Run Code Online (Sandbox Code Playgroud)

最后,这里是我调用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
            });
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

boe*_*m_s 8

根据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
  });
Run Code Online (Sandbox Code Playgroud)


编辑

我刚读了你的编辑,你能帮我试试吗:

删除所有require('./app/models/xxx')你的index.js文件。

在您的模型结束时:

module.exports = mongoose.model('xxx', xxxSchema);
Run Code Online (Sandbox Code Playgroud)

然后在您的路线/控制器中:

const User = require('/app/models/users');
const Borne = require('/app/models/borne');
const Transaction = require('/app/models/transaction');
Run Code Online (Sandbox Code Playgroud)

因此,您的模型与架构同时创建,并且您确定这是正确的顺序。

希望它有帮助,
最好的问候