nodejs中带有Q的承诺保存引用到mongoose
Promises in nodejs with Q save ref to mongoose
需要帮助。有一个猫鼬文件,我从api构建;我需要从另一个猫鼬查询的参考填充国家字段。一切都很好,除了我可以访问我的第一个文档对象在函数中,我用来检索第二个对象
var instituteQelasy;
if (res) {
instituteQelasy = res;
instituteQelasy.name = object.name;
} else {
instituteQelasy = new instituteModel({
name: object.name,
idQelasy: object.id
});
}
if (typeof object.country.id !== 'undefined') {
var country = new countryModel();
var countryRef = country.findByIdQelasy(object.country.id, function(err, res) {
var deferred = Q.defer();
if (err) {
deferred.reject(err);
}
if (res) {
deferred.resolve(res._id);
}
return deferred.promise;
});
countryRef(res).then(function(data) {
instituteQelasy.country = data;
});
}
instituteQelasy.save(function(err) {
if (err)
console.log('something went wrong while saving!');
});
编辑:既然你们指向实习猫鼬。这是我的文件的样子我的country.js是什么样子,为什么我没有使用mongoose promises
var mongoose = require('mongoose');
var env = process.env.NODE_ENV || 'development';
var config = require('../config/config')[env];
var Schema = mongoose.Schema;
var countrySchema = new Schema({
name: {type: String, required: true},
idQelasy: {type: String, required: true},
created_at: {type: Date, default: Date.now}
}, {collection: 'qel_par_country', versionKey: false});
countrySchema.methods.findByIdQelasy = function (id, callback) {
return mongoose.model('Country').findOne().where('idQelasy').equals(id).exec(callback);
}
countrySchema.methods.findByName = function (name, callback) {
return mongoose.model('Country').findOne().where('name').equals(name).exec(callback);
}
mongoose.model('Country', countrySchema);
然后导入到server.js文件中,如下所示
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function (file) {
require(models_path + '/' + file);
});
var countryModel = mongoose.model('Country');
Bergi在正确的轨道上,Mongoose可以返回承诺。但是,findByIdQelasy
不返回承诺。你需要打电话给exec()
来得到一个承诺。
Q(country.findByIdQelasy(object.country.id).exec()).then(function (res) {
instituteQelasy.country = res._id;
});
相关文章:
- 做<img>或者<画布>保存对原始(大)dataUrl对象的引用
- 谷歌地图 API v3.0 保存对标记的引用
- 为什么jQuery's每个循环的函数都保存对元素对象的引用
- 在Javascript中,如何区分与实际数据一起保存的对象和作为引用保存的对象
- 猫鼬JS预保存钩子与引用值
- 使用 Function.prototype.bind 或保存的引用
- 同步代码框 - 调用 API - 解析 JSON - 获取引用 - 保存新对象
- 在哈希数组中保存对 jquery 元素的引用
- 如何保存引用用户对象的分析对象
- 引用下划线模板中 require 模块内保存的枚举值
- 将引用$(this)保存到DB
- 保存对立即调用的函数的引用
- 如何获取模型内部的组件引用保存回调函数
- 我应该如何以JSON格式将当前引用保存到父节点
- 将对象或函数的引用保存为匿名函数的变量的Javascript错误做法
- 保存& # 39;这个# 39;javascript原型事件处理程序中的引用
- 在Backbone中保存对全局集合的引用的最佳模式
- 如何在不保存的情况下更新多个firebase引用
- 保存对内置方法的引用的好处
- nodejs中带有Q的承诺保存引用到mongoose