[英]How to Return Mongoose Object Field (In Module.exports function)
So I have the following code: 所以我有以下代码:
var Mix = require('../models/mix');
module.exports = {
mixTitle: function(mix_id) {
return Mix.findOne({ 'mix_id' : mix_id }, 'title', function(err, mix){
console.log(mix.title); // This correctly prints the title field
return mix.title;
});
}
}
I import the Mix model and then can access the title
field inside my callback, but is there any way to actually return the mix.title
string value? 我导入了Mix模型,然后可以访问回调中的
title
字段,但是有什么方法可以真正返回mix.title
字符串值? Currently all I get is (what I think is) the query prototype .. 目前我得到的只是(我认为是)查询原型..
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'mixes',
collectionName: 'mixes',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
... etc ...等等
How would I properly write this exported function to just return the title field of my found Object? 我如何正确编写此导出函数以仅返回找到的对象的标题字段?
Mix.findOne
is async function, you can get result of function immediately. Mix.findOne
是异步函数,您可以立即获取函数结果。 You can pass callback
parameter and get result there, or much better solution - use promises: 您可以传递
callback
参数并在那里获得结果,或者更好的解决方案-使用promises:
// mix-service.js
var Mix = require('../models/mix');
module.exports = {
mixTitle: function(mix_id) {
return Mix
.findOne({ 'mix_id' : mix_id }, 'title')
.then(mix => {
console.log(mix.title); // This correctly prints the title field
return mix.title;
});
}
};
// calling module
var mixSrvc = require('../mix-service');
mixSrvc
.mixTitle(1)
.then(mixTitle => console.log(mixTitle))
.catch(err => console.log(err));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.