我已经尝试了所有我能想到的方法,但仍然无法将任何数据插入我的 MongoDB 数据库。 当接收数据(推文)时,我记录所有内容以检查数据类型是否与我的架构中的字段类型匹配,这看起来没问题,但插入到我的数据库中的数据只是一个空的 mongodb 文档。
我的架构:
var mongoose = require('mongoose');
var tweetSchema = new mongoose.Schema({
userName: {type: String, required: true},
imageUrl: {type: String},
bannerUrl: {type: String},
text: {type: String},
hashTag: {type: String}
});
module.Exports = tweetSchema;
我的模型:
var mongoose = require("mongoose");
var tweetSchema = require("../schemas/tweet.js");
var Tweet = mongoose.model('Tweet',tweetSchema,"tweets");
module.exports = Tweet;
我尝试将文档插入我的 mongoDB 的应用程序部分:
var Twitter = require('node-tweet-stream');
require("./data/connectDB.js");
var Tweet = require('./data/models/tweet');
t.on('tweet', function(twdata){
var uName = twdata.user.screen_name.toString();
var iUrl = twdata.user.profile_image_url;
var bUrl = twdata.user.profile_banner_url;
var txt = twdata.text;
var htag = "test";
console.log("username: " + uName + " - " + typeof uName);
console.log("image url: " + iUrl + " - " + typeof iUrl);
console.log("banner url: " + bUrl + " - " + typeof bUrl);
console.log("text: " + txt + " - " + typeof txt);
console.log("hashtag: " + htag + " - " + typeof htag);
var newTweet = new Tweet({
userName: uName,
imageUrl: iUrl,
bannerUrl: bUrl,
text: txt,
hashTag: htag
});
console.log(newTweet);
newTweet.save(function(err, newTweet){
if(err){
console.log(err);
}
else{
console.dir(newTweet);
}
});
//console.log(twdata.id);
});
我收到的数据类型和内容的日志:
username: ZBBXXR - string
image url: http://pbs.twimg.com/profile_images/550347979886845953/9aU5othN_normal.jpeg - string
banner url: https://pbs.twimg.com/profile_banners/274821783/1418814026 - string
text: RT @NamiZelmon: happy birthday yoseob oppa💕💕💕🎂🎁🎉🎊 @all4b2uty hope you like this🙈 #HappyYSDay http://t.co/C6W3LFg5F5 - string
hashtag: test - string
我没有收到任何错误,但插入到我的数据库中的文档如下(这只是一个空的 mongoDB 文档):
{ __v: 0, _id: 54a9b1ba0114720c2711cbfc }
最佳答案
我不敢相信我没有看到这个。 在我的架构中我写了
module.Exports = tweetSchema;
虽然它应该是非大写的“导出”
module.exports = tweetSchema;
由于大写拼写错误,在 './model/tweet.js 中调用 require('../schema/tweet.js') 时没有返回任何内容。 因此,将 undefined 传递给 './model/tweet.js' 中的 mongoose.model('Tweet',TweetSchema,"tweets") 并创建空数据库文档。
关于javascript - 无法使用 mongoose、Node.js 将数据插入 mongoDB 中的文档字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770769/