【发布时间】:2017-05-19 07:59:07
【问题描述】:
我正在使用 mongoDB 和 NodeJS 使用 mongoose 包,尝试将对象保存到 DB,其中一个字段丢失...检查了所有内容。
问题:我不知道为什么会这样,我有每个字段,因为它应该根据问题模式保存到数据库中。对于某些方式,当我生成一个新的问题架构对象并将请求的详细信息应用到它时,除了引用的字段(主题)之外的每个字段都适用于新的问题架构。我在这里遗漏了什么吗,我在新问题对象之前检查了所有字段都很好,包括引用的字段 - 显示主题的正确 ID。
我有这个主题架构:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Question = require("./Question.js");
var topic_schema = Schema({
name: {type: String, required: true},
questions: [{ type: Schema.Types.ObjectId, ref: 'Question'}]
});
module.exports = mongoose.model('Topic', topic_schema);
我有这个问题架构:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Topic = require("./Topic.js");
var question_schema = Schema({
syntax: {type: String, required: true},
answer: {type: String, required: true},
topic: [{ type: Schema.Types.ObjectId, ref: 'Topic' }]
});
module.exports = mongoose.model('Question', question_schema);
我正在尝试在这条路线中保存一个问题:
app.post('/addque', function (req,res){
// Getting the details from the client request
var question_details = req.body.question_details;
// Getting the id's of the topics
Topic.find({name: {"$in": question_details.topics}}).select('_id').exec(function (err, topics){
if (err) return console.error(err);
// Apply the id's to the question_details
question_details.topics = topics;
// ~~~~~~~~~~Generate new questions object~~~~~~~~~ topic array does not apply here
var question_to_save = question_details;
//Save it to the DB
question_details.save(function(err, saved_question) {
if (err) return console.error(err);
});
});
});
谢谢你帮助我!
【问题讨论】: