如何使用Mongoose将常规JSON对象转换为Mongo文档?

时间:2022-04-02 08:47:48

I have a JSON Object called parsedSong that I want to convert into a Mongo document using Mongoose.

我有一个名为parsedSong的JSON对象,我想使用Mongoose将其转换为Mongo文档。

var newSong = new Song(parsedSong);

However, this only provides me with a new document that only has an id attribute. How can I make a conversion that doesn't cut my data from parsedSong?

但是,这只为我提供了一个只有id属性的新文档。如何进行不会从parsedSong中删除数据的转换?

1 个解决方案

#1


1  

I assumed you have defined these variables in schema. Then you can make something like this:

我假设你已经在模式中定义了这些变量。然后你可以做这样的事情:

var bestSong = {
    artist: "Seether",
    song: "Careless Whisper"
};

var song = new Song(bestSong);

song.save(function(err) {
    if(err) throw err;
    console.log('saved');
});

And now this song should be in database.

现在这首歌应该在数据库中。

#1


1  

I assumed you have defined these variables in schema. Then you can make something like this:

我假设你已经在模式中定义了这些变量。然后你可以做这样的事情:

var bestSong = {
    artist: "Seether",
    song: "Careless Whisper"
};

var song = new Song(bestSong);

song.save(function(err) {
    if(err) throw err;
    console.log('saved');
});

And now this song should be in database.

现在这首歌应该在数据库中。